From c8caa0180ee2ebe300605d969b9798e12e944d96 Mon Sep 17 00:00:00 2001 From: Julia Feng Date: Thu, 30 Jul 2026 11:44:07 -0700 Subject: [PATCH 1/5] remove --- .../skills/plan-ui-change/SKILL.md | 152 --- .../skills/support-prerendering/SKILL.md | 216 --- .../android-tombstone-symbolication/SKILL.md | 148 --- .../scripts/Symbolicate-Tombstone.ps1 | 749 ----------- .../skills/microbenchmarking/SKILL.md | 137 -- .../references/bdn-internals-and-tuning.md | 132 -- .../references/comparison-strategies.md | 188 --- .../references/diagnosers-and-exporters.md | 143 -- .../references/project-setup-and-running.md | 179 --- .../references/writing-benchmarks.md | 296 ----- .../skills/maui-collectionview/SKILL.md | 470 ------- .../references/collectionview-api.md | 241 ---- .../skills/check-bin-obj-clash/SKILL.md | 315 ----- .../skills/eval-performance/SKILL.md | 129 -- .../skills/msbuild-antipatterns/SKILL.md | 409 ------ .../references/additional-antipatterns.md | 315 ----- .../incremental-build-inputs-outputs.md | 30 - .../references/private-assets.md | 22 - .../skills/migrate-static-to-wrapper/SKILL.md | 237 ---- .../skills/dotnet-aot-compat/SKILL.md | 269 ---- .../dotnet-aot-compat/references/polyfills.md | 43 - .../migrate-dotnet9-to-dotnet10/SKILL.md | 274 ---- .../references/aspnet-core-dotnet9to10.md | 140 -- .../containers-interop-dotnet9to10.md | 63 - .../references/core-libraries-dotnet9to10.md | 93 -- .../references/cryptography-dotnet9to10.md | 79 -- .../references/csharp-compiler-dotnet9to10.md | 118 -- .../references/efcore-dotnet9to10.md | 157 --- .../extensions-hosting-dotnet9to10.md | 75 -- .../references/sdk-msbuild-dotnet9to10.md | 50 - .../serialization-networking-dotnet9to10.md | 61 - .../references/winforms-wpf-dotnet9to10.md | 91 -- tests/dotnet-blazor/plan-ui-change/eval.yaml | 330 ----- .../support-prerendering/eval.yaml | 79 -- .../crashlog_ios.txt | 41 - .../android-tombstone-symbolication/eval.yaml | 219 --- .../tombstone_coreclr.txt | 29 - .../tombstone_multi_buildid.txt | 27 - .../tombstone_multithread.txt | 46 - .../tombstone_nativeaot.txt | 26 - .../tombstone_no_buildid.txt | 25 - .../tombstone_no_dotnet.txt | 20 - .../tombstone_sample.txt | 38 - .../TextAnalyzer/TextAnalyzer.cs | 64 - .../TextAnalyzer/TextAnalyzer.csproj | 7 - tests/dotnet-diag/microbenchmarking/eval.yaml | 38 - .../dotnet-maui/maui-collectionview/eval.yaml | 129 -- .../check-bin-obj-clash/.gitignore | 3 - .../check-bin-obj-clash/ClashTest.slnx | 7 - .../ConsumerApp/Consumer.cs | 6 - .../ConsumerApp/ConsumerApp.csproj | 24 - .../check-bin-obj-clash/LibraryA/ClassA.cs | 6 - .../LibraryA/LibraryA.csproj | 22 - .../check-bin-obj-clash/LibraryB/ClassB.cs | 6 - .../LibraryB/LibraryB.csproj | 22 - .../MultiTargetLib/MultiClass.cs | 13 - .../MultiTargetLib/MultiTargetLib.csproj | 19 - .../check-bin-obj-clash/ToolLib/Tool.cs | 6 - .../ToolLib/ToolLib.csproj | 15 - .../check-bin-obj-clash/eval.yaml | 37 - .../eval-performance/EvalHeavy.csproj | 15 - .../eval-performance/Program.cs | 5 - .../eval-performance/build-notes.txt | 2 - .../dotnet-msbuild/eval-performance/eval.yaml | 29 - .../eval-performance/imports/level1.props | 6 - .../eval-performance/imports/level2.props | 6 - .../eval-performance/imports/level3.props | 5 - .../Directory.Build.props | 19 - .../Directory.Build.targets | 12 - .../msbuild-antipatterns/LibA/Class1.cs | 5 - .../msbuild-antipatterns/LibA/LibA.csproj | 46 - .../msbuild-antipatterns/LibB/Class2.cs | 5 - .../msbuild-antipatterns/LibB/LibB.csproj | 26 - .../msbuild-antipatterns/StyleIssues.sln | 11 - .../msbuild-antipatterns/eval.yaml | 107 -- .../fsharp/BrokenOrder/BrokenOrder.fsproj | 11 - .../fsharp/BrokenOrder/Domain.fs | 15 - .../fsharp/BrokenOrder/Program.fs | 14 - .../fsharp/BrokenOrder/Services.fs | 12 - .../fsharp/Directory.Build.props | 6 - .../fsharp/Directory.Build.targets | 3 - .../fsharp/OrderService/Domain.fs | 15 - .../fsharp/OrderService/OrderService.fsproj | 11 - .../fsharp/OrderService/Program.fs | 14 - .../fsharp/OrderService/Services.fs | 12 - .../migrate-static-to-wrapper/eval.yaml | 183 --- .../fixtures/decline-no-wrapper/DataLoader.cs | 5 - .../decline-no-wrapper/MyProject.csproj | 5 - .../fixtures/ready-to-migrate/Program.cs | 6 - .../ready-to-migrate/ReadyToMigrate.csproj | 7 - .../ready-to-migrate/Services/AuditLogger.cs | 11 - .../Services/CouponService.cs | 51 - .../static-helper/StaticHelper.csproj | 7 - .../Utilities/RetentionPolicy.cs | 27 - .../Billing.Tests/Billing.Tests.csproj | 14 - .../Billing.Tests/SubscriptionServiceTests.cs | 46 - .../with-tests/Billing/Abstractions/IClock.cs | 9 - .../Billing/Abstractions/SystemClock.cs | 6 - .../with-tests/Billing/Billing.csproj | 7 - .../Billing/Services/InvoiceService.cs | 15 - .../Billing/Services/SubscriptionService.cs | 33 - .../dotnet-aot-compat/after/.gitignore | 2 - .../dotnet-aot-compat/after/ArmClient.cs | 315 ----- .../after/ArmClientOptions.cs | 81 -- .../dotnet-aot-compat/after/ArmCollection.cs | 84 -- .../dotnet-aot-compat/after/ArmEnvironment.cs | 82 -- .../dotnet-aot-compat/after/ArmOperation.cs | 116 -- .../after/ArmOperationOfT.cs | 15 - .../dotnet-aot-compat/after/ArmResource.cs | 140 -- .../Assets/Profile/2020-09-01-hybrid.json | 678 ---------- .../after/Azure.ResourceManager.csproj | 31 - .../after/AzureStackProfile.cs | 14 - .../after/BicepModelReaderWriterOptions.cs | 29 - .../after/CodeGenAttributes.cs | 65 - .../after/Common/Custom/Models/ArmPlan.cs | 95 -- .../after/Common/Custom/Models/ArmSku.cs | 95 -- .../Custom/Models/EncryptionProperties.cs | 18 - .../Common/Custom/Models/EncryptionStatus.cs | 18 - .../Custom/Models/KeyVaultProperties.cs | 18 - .../ManagedServiceIdentity.Serialization.cs | 263 ---- .../Custom/Models/ManagedServiceIdentity.cs | 48 - .../Models/ManagedServiceIdentityType.cs | 37 - .../Models/SystemAssignedServiceIdentity.cs | 65 - .../SystemAssignedServiceIdentityType.cs | 17 - .../Custom/ResourceManagerModelFactory.cs | 25 - .../Common/Generated/Internal/Argument.cs | 129 -- .../Internal/BicepSerializationHelpers.cs | 58 - .../Internal/ChangeTrackingDictionary.cs | 167 --- .../Generated/Internal/ChangeTrackingList.cs | 153 --- .../Internal/ModelSerializationExtensions.cs | 407 ------ .../Common/Generated/Internal/Optional.cs | 51 - .../Generated/Internal/WirePathAttribute.cs | 27 - .../Generated/Models/ArmPlan.Serialization.cs | 291 ---- .../after/Common/Generated/Models/ArmPlan.cs | 71 - .../Generated/Models/ArmSku.Serialization.cs | 289 ---- .../after/Common/Generated/Models/ArmSku.cs | 65 - .../Models/ArmSkuTier.Serialization.cs | 32 - .../Common/Generated/Models/ArmSkuTier.cs | 22 - .../Models/AzureResourceManagerContext.cs | 19 - .../Common/Generated/Models/CreatedByType.cs | 57 - .../EncryptionProperties.Serialization.cs | 190 --- .../Generated/Models/EncryptionProperties.cs | 39 - .../Generated/Models/EncryptionStatus.cs | 51 - .../KeyVaultProperties.Serialization.cs | 198 --- .../Generated/Models/KeyVaultProperties.cs | 39 - .../Models/ManagedServiceIdentityType.cs | 57 - .../OperationStatusResult.Serialization.cs | 407 ------ .../Generated/Models/OperationStatusResult.cs | 79 -- .../Models/ResourceData.Serialization.cs | 41 - .../Common/Generated/Models/ResourceData.cs | 45 - ...emAssignedServiceIdentity.Serialization.cs | 210 --- .../Models/SystemAssignedServiceIdentity.cs | 22 - .../SystemAssignedServiceIdentityType.cs | 51 - .../Models/SystemData.Serialization.cs | 326 ----- .../Common/Generated/Models/SystemData.cs | 60 - .../TrackedResourceData.Serialization.cs | 35 - .../Generated/Models/TrackedResourceData.cs | 50 - .../UserAssignedIdentity.Serialization.cs | 190 --- .../Generated/Models/UserAssignedIdentity.cs | 40 - .../after/Directory.Build.props | 2 - .../after/Directory.Packages.props | 10 - .../after/ExperimentalAttribute.cs | 60 - .../Extensions/ArmClientBuilderExtensions.cs | 35 - .../after/GenericOperationSource.cs | 44 - .../Custom/HelperSuppressions.cs | 13 - .../Custom/ManagementGroupResource.cs | 26 - .../ManagementGroupNameAvailabilityContent.cs | 18 - .../Generated/Extensions/ArmClient.cs | 39 - .../Generated/Extensions/TenantResource.cs | 98 -- .../Generated/Internal/WirePathAttribute.cs | 27 - .../ManagementGroupOperationSource.cs | 36 - .../ManagementGroupsArmOperation.cs | 94 -- .../ManagementGroupsArmOperationOfT.cs | 100 -- .../Generated/ManagementGroupCollection.cs | 688 ---------- .../ManagementGroupData.Serialization.cs | 383 ------ .../Generated/ManagementGroupData.cs | 92 -- .../ManagementGroupResource.Serialization.cs | 29 - .../Generated/ManagementGroupResource.cs | 505 ------- .../ManagementGroupSubscriptionCollection.cs | 516 ------- ...mentGroupSubscriptionData.Serialization.cs | 377 ------ .../ManagementGroupSubscriptionData.cs | 97 -- ...GroupSubscriptionResource.Serialization.cs | 29 - .../ManagementGroupSubscriptionResource.cs | 357 ----- ...ateManagementGroupDetails.Serialization.cs | 174 --- .../Models/CreateManagementGroupDetails.cs | 81 -- .../Models/DescendantData.Serialization.cs | 318 ----- .../Generated/Models/DescendantData.cs | 82 -- .../DescendantListResult.Serialization.cs | 219 --- .../Generated/Models/DescendantListResult.cs | 70 - ...DescendantParentGroupInfo.Serialization.cs | 166 --- .../Models/DescendantParentGroupInfo.cs | 67 - .../Models/EntityData.Serialization.cs | 686 ---------- .../Generated/Models/EntityData.cs | 126 -- .../Models/EntityListResult.Serialization.cs | 249 ---- .../Generated/Models/EntityListResult.cs | 74 -- .../Models/EntityPermission.Serialization.cs | 32 - .../Generated/Models/EntityPermission.cs | 22 - .../Generated/Models/EntitySearchOption.cs | 60 - .../Generated/Models/EntityViewOption.cs | 57 - ...ptionUnderManagementGroup.Serialization.cs | 219 --- .../ListSubscriptionUnderManagementGroup.cs | 70 - .../ManagementGroupChildInfo.Serialization.cs | 308 ----- .../Models/ManagementGroupChildInfo.cs | 87 -- ...nagementGroupChildOptions.Serialization.cs | 197 --- .../Models/ManagementGroupChildOptions.cs | 87 -- .../Models/ManagementGroupChildType.cs | 51 - ...gementGroupCollectionGetEntitiesOptions.cs | 57 - ...roupCreateOrUpdateContent.Serialization.cs | 264 ---- .../ManagementGroupCreateOrUpdateContent.cs | 98 -- .../Models/ManagementGroupExpandType.cs | 54 - .../ManagementGroupInfo.Serialization.cs | 451 ------- .../Generated/Models/ManagementGroupInfo.cs | 99 -- ...ManagementGroupListResult.Serialization.cs | 219 --- .../Models/ManagementGroupListResult.cs | 70 - ...upNameAvailabilityContent.Serialization.cs | 144 -- .../ManagementGroupNameAvailabilityContent.cs | 67 - ...oupNameAvailabilityResult.Serialization.cs | 231 ---- .../ManagementGroupNameAvailabilityResult.cs | 76 -- ...roupNameUnavailableReason.Serialization.cs | 28 - .../ManagementGroupNameUnavailableReason.cs | 18 - ...tGroupParentCreateOptions.Serialization.cs | 151 --- .../ManagementGroupParentCreateOptions.cs | 76 -- .../ManagementGroupPatch.Serialization.cs | 164 --- .../Generated/Models/ManagementGroupPatch.cs | 71 - ...anagementGroupPathElement.Serialization.cs | 204 --- .../Models/ManagementGroupPathElement.cs | 71 - ...ParentManagementGroupInfo.Serialization.cs | 238 ---- .../Models/ParentManagementGroupInfo.cs | 76 -- .../Generated/ResourceManagerModelFactory.cs | 269 ---- .../RestOperations/EntitiesRestOperations.cs | 337 ----- ...agementGroupSubscriptionsRestOperations.cs | 517 ------- .../ManagementGroupsRestOperations.cs | 897 ------------- .../after/Properties/AssemblyInfo.cs | 11 - .../after/ProviderConstants.cs | 14 - .../after/RehydrationOperation.cs | 39 - .../after/RehydrationOperationOfT.cs | 42 - .../after/ResourceManagerExtensions.cs | 50 - .../after/ResourceManagerJsonContext.cs | 37 - .../after/Resources/Custom/ArmClient.cs | 26 - .../Resources/Custom/ArmRestApiCollection.cs | 129 -- .../Custom/Extensions/ArmResource.cs | 20 - .../after/Resources/Custom/FeatureResource.cs | 26 - .../after/Resources/Custom/GenericResource.cs | 433 ------ .../Custom/GenericResourceCollection.cs | 266 ---- .../Resources/Custom/GenericResourceData.cs | 14 - .../Resources/Custom/HelperSuppressions.cs | 12 - .../Custom/Models/ArmRestApi.Serialization.cs | 159 --- .../Resources/Custom/Models/ArmRestApi.cs | 49 - .../ArmRestApiListResult.Serialization.cs | 40 - .../Custom/Models/ArmRestApiListResult.cs | 32 - .../Custom/Models/EnforcementMode.cs | 20 - .../Custom/Models/LocationExpanded.cs | 46 - .../Custom/Models/LocationMetadata.cs | 67 - .../Custom/Models/ResourcesMoveContent.cs | 17 - .../Resources/Custom/Models/ResourcesSku.cs | 14 - .../Models/SubResource.Serialization.cs | 112 -- .../Resources/Custom/Models/SubResource.cs | 36 - .../after/Resources/Custom/Models/Tag.cs | 20 - .../WritableSubResource.Serialization.cs | 119 -- .../Custom/Models/WritableSubResource.cs | 36 - .../Resources/Custom/PolicyAssignmentData.cs | 48 - .../Custom/PolicyAssignmentResource.cs | 96 -- .../Resources/Custom/ResourceGroupBuilder.cs | 133 -- .../Custom/ResourceGroupCollection.cs | 39 - .../Resources/Custom/ResourceGroupResource.cs | 110 -- .../Custom/ResourceManagerModelFactory.cs | 42 - .../Custom/ResourceProviderCollection.cs | 152 --- .../Resources/Custom/ResourceProviderData.cs | 63 - .../Custom/ResourceProviderResource.cs | 19 - .../Custom/RestOperations/RestOperations.cs | 107 -- .../RestOperations/TenantsRestOperations.cs | 19 - .../Resources/Custom/SubscriptionData.cs | 18 - .../Resources/Custom/SubscriptionResource.cs | 118 -- .../after/Resources/Custom/TagResource.cs | 70 - .../Resources/Custom/TenantCollection.cs | 28 - .../after/Resources/Custom/TenantResource.cs | 137 -- .../Generated/DataPolicyManifestCollection.cs | 396 ------ .../DataPolicyManifestData.Serialization.cs | 647 --------- .../Generated/DataPolicyManifestData.cs | 117 -- ...ataPolicyManifestResource.Serialization.cs | 29 - .../Generated/DataPolicyManifestResource.cs | 168 --- .../Generated/Extensions/ArmClient.cs | 183 --- .../Generated/Extensions/ArmResource.cs | 156 --- .../Extensions/ManagementGroupResource.cs | 156 --- .../Resources/Generated/FeatureCollection.cs | 394 ------ .../Generated/FeatureData.Serialization.cs | 244 ---- .../after/Resources/Generated/FeatureData.cs | 81 -- .../FeatureResource.Serialization.cs | 29 - .../Resources/Generated/FeatureResource.cs | 316 ----- .../GenericResourceData.Serialization.cs | 609 --------- .../Generated/GenericResourceData.cs | 121 -- .../Internal/Utf8JsonRequestContent.cs | 55 - .../Generated/Internal/WirePathAttribute.cs | 27 - .../GenericResourceOperationSource.cs | 36 - ...esourceGroupExportResultOperationSource.cs | 30 - .../ResourcesArmOperation.cs | 94 -- .../ResourcesArmOperationOfT.cs | 103 -- .../TagResourceOperationSource.cs | 36 - ...nagementGroupPolicyDefinitionCollection.cs | 501 ------- ...pPolicyDefinitionResource.Serialization.cs | 29 - ...ManagementGroupPolicyDefinitionResource.cs | 354 ----- ...ementGroupPolicySetDefinitionCollection.cs | 501 ------- ...licySetDefinitionResource.Serialization.cs | 29 - ...agementGroupPolicySetDefinitionResource.cs | 354 ----- .../Generated/ManagementLockCollection.cs | 488 ------- .../ManagementLockData.Serialization.cs | 334 ----- .../Resources/Generated/ManagementLockData.cs | 94 -- .../ManagementLockResource.Serialization.cs | 29 - .../Generated/ManagementLockResource.cs | 353 ----- .../Models/ApiProfile.Serialization.cs | 204 --- .../Resources/Generated/Models/ApiProfile.cs | 71 - .../ArmPolicyParameter.Serialization.cs | 306 ----- .../Generated/Models/ArmPolicyParameter.cs | 140 -- .../Models/ArmPolicyParameterType.cs | 66 - .../ArmPolicyParameterValue.Serialization.cs | 173 --- .../Models/ArmPolicyParameterValue.cs | 95 -- .../AvailabilityZoneMappings.Serialization.cs | 204 --- .../Models/AvailabilityZoneMappings.cs | 71 - .../AzureRoleDefinition.Serialization.cs | 351 ----- .../Generated/Models/AzureRoleDefinition.cs | 88 -- ...esourceFunctionDefinition.Serialization.cs | 293 ---- ...anifestCustomResourceFunctionDefinition.cs | 83 -- .../DataPolicyManifestEffect.Serialization.cs | 207 --- .../Models/DataPolicyManifestEffect.cs | 100 -- ...aPolicyManifestListResult.Serialization.cs | 219 --- .../Models/DataPolicyManifestListResult.cs | 70 - .../Generated/Models/EnforcementMode.cs | 51 - .../Models/ExportTemplate.Serialization.cs | 154 --- .../Generated/Models/ExportTemplate.cs | 72 - .../Models/ExtendedLocation.Serialization.cs | 194 --- .../Generated/Models/ExtendedLocation.cs | 39 - .../Generated/Models/ExtendedLocationType.cs | 48 - ...atureOperationsListResult.Serialization.cs | 219 --- .../Models/FeatureOperationsListResult.cs | 70 - .../Models/FeatureProperties.Serialization.cs | 170 --- .../Generated/Models/FeatureProperties.cs | 66 - .../Models/LocationExpanded.Serialization.cs | 409 ------ .../Generated/Models/LocationExpanded.cs | 102 -- .../LocationListResult.Serialization.cs | 185 --- .../Generated/Models/LocationListResult.cs | 66 - .../Models/LocationMetadata.Serialization.cs | 443 ------ .../Generated/Models/LocationMetadata.cs | 101 -- .../Models/LocationType.Serialization.cs | 28 - .../Generated/Models/LocationType.cs | 18 - .../Models/ManagedByTenant.Serialization.cs | 166 --- .../Generated/Models/ManagedByTenant.cs | 66 - .../Generated/Models/ManagementLockLevel.cs | 54 - .../ManagementLockListResult.Serialization.cs | 219 --- .../Models/ManagementLockListResult.cs | 70 - .../ManagementLockOwner.Serialization.cs | 170 --- .../Generated/Models/ManagementLockOwner.cs | 66 - .../NonComplianceMessage.Serialization.cs | 201 --- .../Generated/Models/NonComplianceMessage.cs | 81 -- .../Models/PairedRegion.Serialization.cs | 238 ---- .../Generated/Models/PairedRegion.cs | 76 -- ...rDefinitionsValueMetadata.Serialization.cs | 263 ---- .../ParameterDefinitionsValueMetadata.cs | 82 -- .../Models/Permission.Serialization.cs | 381 ------ .../Resources/Generated/Models/Permission.cs | 85 -- ...olicyAssignmentListResult.Serialization.cs | 219 --- .../Models/PolicyAssignmentListResult.cs | 70 - .../PolicyAssignmentPatch.Serialization.cs | 214 --- .../Generated/Models/PolicyAssignmentPatch.cs | 85 -- .../PolicyDefinitionGroup.Serialization.cs | 309 ----- .../Generated/Models/PolicyDefinitionGroup.cs | 96 -- ...olicyDefinitionListResult.Serialization.cs | 219 --- .../Models/PolicyDefinitionListResult.cs | 70 - ...PolicyDefinitionReference.Serialization.cs | 313 ----- .../Models/PolicyDefinitionReference.cs | 93 -- .../Models/PolicyOverride.Serialization.cs | 249 ---- .../Generated/Models/PolicyOverride.cs | 77 -- .../Generated/Models/PolicyOverrideKind.cs | 48 - ...cySetDefinitionListResult.Serialization.cs | 219 --- .../Models/PolicySetDefinitionListResult.cs | 70 - .../Resources/Generated/Models/PolicyType.cs | 57 - .../Models/PredefinedTag.Serialization.cs | 283 ---- .../Generated/Models/PredefinedTag.cs | 82 -- .../PredefinedTagCount.Serialization.cs | 200 --- .../Generated/Models/PredefinedTagCount.cs | 71 - .../PredefinedTagValue.Serialization.cs | 234 ---- .../Generated/Models/PredefinedTagValue.cs | 76 -- .../PredefinedTagsListResult.Serialization.cs | 219 --- .../Models/PredefinedTagsListResult.cs | 70 - .../ProviderAuthorizationConsentState.cs | 57 - ...ProviderConsentDefinition.Serialization.cs | 133 -- .../Models/ProviderConsentDefinition.cs | 66 - .../ProviderExtendedLocation.Serialization.cs | 262 ---- .../Models/ProviderExtendedLocation.cs | 78 -- .../ProviderPermission.Serialization.cs | 260 ---- .../Generated/Models/ProviderPermission.cs | 81 -- ...viderPermissionListResult.Serialization.cs | 219 --- .../Models/ProviderPermissionListResult.cs | 72 - ...oviderRegistrationContent.Serialization.cs | 133 -- .../Models/ProviderRegistrationContent.cs | 77 -- .../ProviderResourceType.Serialization.cs | 627 --------- .../Generated/Models/ProviderResourceType.cs | 118 -- ...derResourceTypeListResult.Serialization.cs | 219 --- .../Models/ProviderResourceTypeListResult.cs | 72 - .../Generated/Models/RegionCategory.cs | 54 - .../Resources/Generated/Models/RegionType.cs | 51 - ...ResourceGroupExportResult.Serialization.cs | 203 --- .../Models/ResourceGroupExportResult.cs | 100 -- .../ResourceGroupListResult.Serialization.cs | 219 --- .../Models/ResourceGroupListResult.cs | 70 - .../ResourceGroupPatch.Serialization.cs | 181 --- .../Generated/Models/ResourceGroupPatch.cs | 88 -- .../ResourceGroupProperties.Serialization.cs | 170 --- .../Models/ResourceGroupProperties.cs | 66 - .../ResourceListResult.Serialization.cs | 219 --- .../Generated/Models/ResourceListResult.cs | 70 - ...urceNameValidationContent.Serialization.cs | 134 -- .../Models/ResourceNameValidationContent.cs | 84 -- ...ourceNameValidationResult.Serialization.cs | 230 ---- .../Models/ResourceNameValidationResult.cs | 77 -- .../Models/ResourceNameValidationStatus.cs | 51 - ...esourceProviderListResult.Serialization.cs | 219 --- .../Models/ResourceProviderListResult.cs | 70 - .../Models/ResourceSelector.Serialization.cs | 219 --- .../Generated/Models/ResourceSelector.cs | 72 - ...esourceSelectorExpression.Serialization.cs | 289 ---- .../Models/ResourceSelectorExpression.cs | 78 -- .../Generated/Models/ResourceSelectorKind.cs | 57 - .../Models/ResourceTypeAlias.Serialization.cs | 350 ----- .../Generated/Models/ResourceTypeAlias.cs | 92 -- .../ResourceTypeAliasPath.Serialization.cs | 292 ---- .../Generated/Models/ResourceTypeAliasPath.cs | 82 -- .../Models/ResourceTypeAliasPathAttributes.cs | 51 - ...urceTypeAliasPathMetadata.Serialization.cs | 196 --- .../Models/ResourceTypeAliasPathMetadata.cs | 71 - .../Models/ResourceTypeAliasPathTokenType.cs | 69 - .../ResourceTypeAliasPattern.Serialization.cs | 234 ---- .../Models/ResourceTypeAliasPattern.cs | 76 -- ...ourceTypeAliasPatternType.Serialization.cs | 28 - .../Models/ResourceTypeAliasPatternType.cs | 18 - .../ResourceTypeAliasType.Serialization.cs | 30 - .../Generated/Models/ResourceTypeAliasType.cs | 20 - .../ResourceTypeAliases.Serialization.cs | 219 --- .../Generated/Models/ResourceTypeAliases.cs | 72 - .../ResourcesMoveContent.Serialization.cs | 158 --- .../Generated/Models/ResourcesMoveContent.cs | 73 - .../Models/ResourcesSku.Serialization.cs | 343 ----- .../Generated/Models/ResourcesSku.cs | 91 -- .../Models/SpendingLimit.Serialization.cs | 30 - .../Generated/Models/SpendingLimit.cs | 20 - .../Resources/Generated/Models/SubResource.cs | 58 - .../SubscriptionListResult.Serialization.cs | 216 --- .../Models/SubscriptionListResult.cs | 80 -- .../SubscriptionPolicies.Serialization.cs | 234 ---- .../Generated/Models/SubscriptionPolicies.cs | 76 -- .../Models/SubscriptionState.Serialization.cs | 34 - .../Generated/Models/SubscriptionState.cs | 24 - .../Generated/Models/Tag.Serialization.cs | 200 --- .../after/Resources/Generated/Models/Tag.cs | 63 - .../Generated/Models/TagPatchMode.cs | 54 - .../Models/TagResourcePatch.Serialization.cs | 148 --- .../Generated/Models/TagResourcePatch.cs | 81 -- .../Models/TenantCategory.Serialization.cs | 30 - .../Generated/Models/TenantCategory.cs | 20 - .../Models/TenantListResult.Serialization.cs | 216 --- .../Generated/Models/TenantListResult.cs | 80 -- .../TenantResourceProvider.Serialization.cs | 219 --- .../Models/TenantResourceProvider.cs | 72 - ...esourceProviderListResult.Serialization.cs | 219 --- .../TenantResourceProviderListResult.cs | 70 - ...ackedResourceExtendedData.Serialization.cs | 313 ----- .../Models/TrackedResourceExtendedData.cs | 80 -- .../Models/ZoneMapping.Serialization.cs | 228 ---- .../Resources/Generated/Models/ZoneMapping.cs | 73 - .../Generated/PolicyAssignmentCollection.cs | 630 --------- .../PolicyAssignmentData.Serialization.cs | 760 ----------- .../Generated/PolicyAssignmentData.cs | 170 --- .../PolicyAssignmentResource.Serialization.cs | 29 - .../Generated/PolicyAssignmentResource.cs | 342 ----- .../PolicyDefinitionData.Serialization.cs | 492 ------- .../Generated/PolicyDefinitionData.cs | 165 --- .../PolicySetDefinitionData.Serialization.cs | 517 ------- .../Generated/PolicySetDefinitionData.cs | 138 -- .../Generated/ResourceGroupCollection.cs | 500 ------- .../ResourceGroupData.Serialization.cs | 352 ----- .../Resources/Generated/ResourceGroupData.cs | 95 -- .../ResourceGroupResource.Serialization.cs | 29 - .../Generated/ResourceGroupResource.cs | 980 -------------- .../Generated/ResourceManagerModelFactory.cs | 764 ----------- .../Generated/ResourceProviderCollection.cs | 389 ------ .../ResourceProviderData.Serialization.cs | 355 ----- .../Generated/ResourceProviderData.cs | 87 -- .../ResourceProviderResource.Serialization.cs | 29 - .../Generated/ResourceProviderResource.cs | 509 ------- .../DataPolicyManifestsRestOperations.cs | 265 ---- .../RestOperations/FeaturesRestOperations.cs | 643 --------- .../ManagementLocksRestOperations.cs | 459 ------- .../PolicyAssignmentsRestOperations.cs | 1183 ----------------- .../PolicyDefinitionsRestOperations.cs | 1145 ---------------- .../PolicySetDefinitionsRestOperations.cs | 1149 ---------------- .../ProviderResourceTypesRestOperations.cs | 135 -- .../RestOperations/ProvidersRestOperations.cs | 802 ----------- .../ResourceGroupsRestOperations.cs | 663 --------- .../ResourceManagementRestOperations.cs | 112 -- .../RestOperations/ResourcesRestOperations.cs | 915 ------------- .../SubscriptionsRestOperations.cs | 341 ----- .../RestOperations/TagsRestOperations.cs | 833 ------------ .../RestOperations/TenantsRestOperations.cs | 182 --- .../Generated/SubscriptionCollection.cs | 394 ------ .../SubscriptionData.Serialization.cs | 481 ------- .../Resources/Generated/SubscriptionData.cs | 109 -- .../SubscriptionPolicyDefinitionCollection.cs | 500 ------- ...nPolicyDefinitionResource.Serialization.cs | 29 - .../SubscriptionPolicyDefinitionResource.cs | 353 ----- ...bscriptionPolicySetDefinitionCollection.cs | 500 ------- ...licySetDefinitionResource.Serialization.cs | 29 - ...SubscriptionPolicySetDefinitionResource.cs | 353 ----- .../SubscriptionResource.Serialization.cs | 29 - .../Generated/SubscriptionResource.cs | 962 -------------- .../Generated/TagResource.Serialization.cs | 29 - .../after/Resources/Generated/TagResource.cs | 437 ------ .../TagResourceData.Serialization.cs | 237 ---- .../Resources/Generated/TagResourceData.cs | 96 -- .../Resources/Generated/TenantCollection.cs | 199 --- .../Generated/TenantData.Serialization.cs | 504 ------- .../after/Resources/Generated/TenantData.cs | 116 -- .../TenantPolicyDefinitionCollection.cs | 398 ------ ...tPolicyDefinitionResource.Serialization.cs | 29 - .../TenantPolicyDefinitionResource.cs | 168 --- .../TenantPolicySetDefinitionCollection.cs | 398 ------ ...licySetDefinitionResource.Serialization.cs | 29 - .../TenantPolicySetDefinitionResource.cs | 168 --- .../Generated/TenantResource.Serialization.cs | 29 - .../Resources/Generated/TenantResource.cs | 505 ------- .../after/Shared/AppContextSwitchHelper.cs | 42 - .../after/Shared/AsyncLockWithValue.cs | 260 ---- ...AzureResourceProviderNamespaceAttribute.cs | 22 - .../after/Shared/ClientDiagnostics.cs | 73 - .../after/Shared/DiagnosticScope.cs | 448 ------- .../after/Shared/DiagnosticScopeFactory.cs | 103 -- .../Shared/FixedDelayWithNoJitterStrategy.cs | 26 - .../Shared/ForwardsClientCallsAttribute.cs | 39 - .../after/Shared/HashCodeBuilder.cs | 387 ------ .../after/Shared/HttpMessageSanitizer.cs | 198 --- .../after/Shared/HttpPipelineExtensions.cs | 110 -- .../after/Shared/IOperationSource.cs | 14 - .../after/Shared/IUtf8JsonSerializable.cs | 14 - .../InitializationConstructorAttribute.cs | 15 - .../ManagedServiceIdentityTypeV3Converter.cs | 53 - .../Shared/NextLinkOperationImplementation.cs | 701 ---------- .../after/Shared/NoValueResponseOfT.cs | 39 - .../after/Shared/OperationFinalStateVia.cs | 16 - .../after/Shared/OperationInternal.cs | 263 ---- .../after/Shared/OperationInternalBase.cs | 234 ---- .../after/Shared/OperationInternalOfT.cs | 431 ------ .../after/Shared/OperationPoller.cs | 114 -- .../dotnet-aot-compat/after/Shared/Page.cs | 16 - .../after/Shared/PageableHelpers.cs | 556 -------- .../Shared/PropertyReferenceTypeAttribute.cs | 52 - .../after/Shared/ProtocolOperation.cs | 78 -- .../after/Shared/RawRequestUriBuilder.cs | 229 ---- .../after/Shared/ReferenceTypeAttribute.cs | 36 - .../after/Shared/ResponseErrorConverter.cs | 70 - .../after/Shared/SequentialDelayStrategy.cs | 38 - .../SerializationConstructorAttribute.cs | 15 - .../after/Shared/SharedExtensions.cs | 82 -- .../after/Shared/TaskExtensions.cs | 313 ----- .../after/Shared/TypeFormatters.cs | 159 --- .../Shared/TypeReferenceTypeAttribute.cs | 41 - .../after/Shared/VoidValue.cs | 10 - .../dotnet-aot-compat/after/autorest.md | 839 ------------ .../dotnet-aot-compat/after/global.json | 6 - .../dotnet-aot-compat/before/.gitignore | 2 - .../dotnet-aot-compat/before/ArmClient.cs | 315 ----- .../before/ArmClientOptions.cs | 81 -- .../dotnet-aot-compat/before/ArmCollection.cs | 84 -- .../before/ArmEnvironment.cs | 82 -- .../dotnet-aot-compat/before/ArmOperation.cs | 113 -- .../before/ArmOperationOfT.cs | 15 - .../dotnet-aot-compat/before/ArmResource.cs | 140 -- .../Assets/Profile/2020-09-01-hybrid.json | 678 ---------- .../before/Azure.ResourceManager.csproj | 30 - .../before/AzureStackProfile.cs | 14 - .../before/BicepModelReaderWriterOptions.cs | 29 - .../before/CodeGenAttributes.cs | 65 - .../before/Common/Custom/Models/ArmPlan.cs | 95 -- .../before/Common/Custom/Models/ArmSku.cs | 95 -- .../Custom/Models/EncryptionProperties.cs | 18 - .../Common/Custom/Models/EncryptionStatus.cs | 18 - .../Custom/Models/KeyVaultProperties.cs | 18 - .../ManagedServiceIdentity.Serialization.cs | 263 ---- .../Custom/Models/ManagedServiceIdentity.cs | 48 - .../Models/ManagedServiceIdentityType.cs | 37 - .../Models/SystemAssignedServiceIdentity.cs | 65 - .../SystemAssignedServiceIdentityType.cs | 17 - .../Custom/ResourceManagerModelFactory.cs | 25 - .../Common/Generated/Internal/Argument.cs | 129 -- .../Internal/BicepSerializationHelpers.cs | 58 - .../Internal/ChangeTrackingDictionary.cs | 167 --- .../Generated/Internal/ChangeTrackingList.cs | 153 --- .../Internal/ModelSerializationExtensions.cs | 407 ------ .../Common/Generated/Internal/Optional.cs | 51 - .../Generated/Internal/WirePathAttribute.cs | 27 - .../Generated/Models/ArmPlan.Serialization.cs | 291 ---- .../before/Common/Generated/Models/ArmPlan.cs | 71 - .../Generated/Models/ArmSku.Serialization.cs | 289 ---- .../before/Common/Generated/Models/ArmSku.cs | 65 - .../Models/ArmSkuTier.Serialization.cs | 32 - .../Common/Generated/Models/ArmSkuTier.cs | 22 - .../Models/AzureResourceManagerContext.cs | 19 - .../Common/Generated/Models/CreatedByType.cs | 57 - .../EncryptionProperties.Serialization.cs | 190 --- .../Generated/Models/EncryptionProperties.cs | 39 - .../Generated/Models/EncryptionStatus.cs | 51 - .../KeyVaultProperties.Serialization.cs | 198 --- .../Generated/Models/KeyVaultProperties.cs | 39 - .../Models/ManagedServiceIdentityType.cs | 57 - .../OperationStatusResult.Serialization.cs | 407 ------ .../Generated/Models/OperationStatusResult.cs | 79 -- .../Models/ResourceData.Serialization.cs | 41 - .../Common/Generated/Models/ResourceData.cs | 45 - ...emAssignedServiceIdentity.Serialization.cs | 210 --- .../Models/SystemAssignedServiceIdentity.cs | 22 - .../SystemAssignedServiceIdentityType.cs | 51 - .../Models/SystemData.Serialization.cs | 326 ----- .../Common/Generated/Models/SystemData.cs | 60 - .../TrackedResourceData.Serialization.cs | 35 - .../Generated/Models/TrackedResourceData.cs | 50 - .../UserAssignedIdentity.Serialization.cs | 190 --- .../Generated/Models/UserAssignedIdentity.cs | 40 - .../before/Directory.Build.props | 2 - .../before/Directory.Packages.props | 10 - .../before/ExperimentalAttribute.cs | 60 - .../Extensions/ArmClientBuilderExtensions.cs | 33 - .../before/GenericOperationSource.cs | 44 - .../Custom/HelperSuppressions.cs | 13 - .../Custom/ManagementGroupResource.cs | 26 - .../ManagementGroupNameAvailabilityContent.cs | 18 - .../Generated/Extensions/ArmClient.cs | 39 - .../Generated/Extensions/TenantResource.cs | 98 -- .../Generated/Internal/WirePathAttribute.cs | 27 - .../ManagementGroupOperationSource.cs | 36 - .../ManagementGroupsArmOperation.cs | 94 -- .../ManagementGroupsArmOperationOfT.cs | 100 -- .../Generated/ManagementGroupCollection.cs | 688 ---------- .../ManagementGroupData.Serialization.cs | 383 ------ .../Generated/ManagementGroupData.cs | 92 -- .../ManagementGroupResource.Serialization.cs | 29 - .../Generated/ManagementGroupResource.cs | 505 ------- .../ManagementGroupSubscriptionCollection.cs | 516 ------- ...mentGroupSubscriptionData.Serialization.cs | 377 ------ .../ManagementGroupSubscriptionData.cs | 97 -- ...GroupSubscriptionResource.Serialization.cs | 29 - .../ManagementGroupSubscriptionResource.cs | 357 ----- ...ateManagementGroupDetails.Serialization.cs | 174 --- .../Models/CreateManagementGroupDetails.cs | 81 -- .../Models/DescendantData.Serialization.cs | 318 ----- .../Generated/Models/DescendantData.cs | 82 -- .../DescendantListResult.Serialization.cs | 219 --- .../Generated/Models/DescendantListResult.cs | 70 - ...DescendantParentGroupInfo.Serialization.cs | 166 --- .../Models/DescendantParentGroupInfo.cs | 67 - .../Models/EntityData.Serialization.cs | 686 ---------- .../Generated/Models/EntityData.cs | 126 -- .../Models/EntityListResult.Serialization.cs | 249 ---- .../Generated/Models/EntityListResult.cs | 74 -- .../Models/EntityPermission.Serialization.cs | 32 - .../Generated/Models/EntityPermission.cs | 22 - .../Generated/Models/EntitySearchOption.cs | 60 - .../Generated/Models/EntityViewOption.cs | 57 - ...ptionUnderManagementGroup.Serialization.cs | 219 --- .../ListSubscriptionUnderManagementGroup.cs | 70 - .../ManagementGroupChildInfo.Serialization.cs | 308 ----- .../Models/ManagementGroupChildInfo.cs | 87 -- ...nagementGroupChildOptions.Serialization.cs | 197 --- .../Models/ManagementGroupChildOptions.cs | 87 -- .../Models/ManagementGroupChildType.cs | 51 - ...gementGroupCollectionGetEntitiesOptions.cs | 57 - ...roupCreateOrUpdateContent.Serialization.cs | 264 ---- .../ManagementGroupCreateOrUpdateContent.cs | 98 -- .../Models/ManagementGroupExpandType.cs | 54 - .../ManagementGroupInfo.Serialization.cs | 451 ------- .../Generated/Models/ManagementGroupInfo.cs | 99 -- ...ManagementGroupListResult.Serialization.cs | 219 --- .../Models/ManagementGroupListResult.cs | 70 - ...upNameAvailabilityContent.Serialization.cs | 144 -- .../ManagementGroupNameAvailabilityContent.cs | 67 - ...oupNameAvailabilityResult.Serialization.cs | 231 ---- .../ManagementGroupNameAvailabilityResult.cs | 76 -- ...roupNameUnavailableReason.Serialization.cs | 28 - .../ManagementGroupNameUnavailableReason.cs | 18 - ...tGroupParentCreateOptions.Serialization.cs | 151 --- .../ManagementGroupParentCreateOptions.cs | 76 -- .../ManagementGroupPatch.Serialization.cs | 164 --- .../Generated/Models/ManagementGroupPatch.cs | 71 - ...anagementGroupPathElement.Serialization.cs | 204 --- .../Models/ManagementGroupPathElement.cs | 71 - ...ParentManagementGroupInfo.Serialization.cs | 238 ---- .../Models/ParentManagementGroupInfo.cs | 76 -- .../Generated/ResourceManagerModelFactory.cs | 269 ---- .../RestOperations/EntitiesRestOperations.cs | 337 ----- ...agementGroupSubscriptionsRestOperations.cs | 517 ------- .../ManagementGroupsRestOperations.cs | 897 ------------- .../before/Properties/AssemblyInfo.cs | 11 - .../before/ProviderConstants.cs | 14 - .../before/RehydrationOperation.cs | 39 - .../before/RehydrationOperationOfT.cs | 42 - .../before/ResourceManagerExtensions.cs | 50 - .../before/Resources/Custom/ArmClient.cs | 26 - .../Resources/Custom/ArmRestApiCollection.cs | 129 -- .../Custom/Extensions/ArmResource.cs | 20 - .../Resources/Custom/FeatureResource.cs | 26 - .../Resources/Custom/GenericResource.cs | 433 ------ .../Custom/GenericResourceCollection.cs | 266 ---- .../Resources/Custom/GenericResourceData.cs | 14 - .../Resources/Custom/HelperSuppressions.cs | 12 - .../Custom/Models/ArmRestApi.Serialization.cs | 159 --- .../Resources/Custom/Models/ArmRestApi.cs | 49 - .../ArmRestApiListResult.Serialization.cs | 40 - .../Custom/Models/ArmRestApiListResult.cs | 32 - .../Custom/Models/EnforcementMode.cs | 20 - .../Custom/Models/LocationExpanded.cs | 46 - .../Custom/Models/LocationMetadata.cs | 67 - .../Custom/Models/ResourcesMoveContent.cs | 17 - .../Resources/Custom/Models/ResourcesSku.cs | 14 - .../Models/SubResource.Serialization.cs | 112 -- .../Resources/Custom/Models/SubResource.cs | 36 - .../before/Resources/Custom/Models/Tag.cs | 20 - .../WritableSubResource.Serialization.cs | 119 -- .../Custom/Models/WritableSubResource.cs | 36 - .../Resources/Custom/PolicyAssignmentData.cs | 48 - .../Custom/PolicyAssignmentResource.cs | 96 -- .../Resources/Custom/ResourceGroupBuilder.cs | 133 -- .../Custom/ResourceGroupCollection.cs | 39 - .../Resources/Custom/ResourceGroupResource.cs | 110 -- .../Custom/ResourceManagerModelFactory.cs | 42 - .../Custom/ResourceProviderCollection.cs | 152 --- .../Resources/Custom/ResourceProviderData.cs | 63 - .../Custom/ResourceProviderResource.cs | 19 - .../Custom/RestOperations/RestOperations.cs | 107 -- .../RestOperations/TenantsRestOperations.cs | 19 - .../Resources/Custom/SubscriptionData.cs | 18 - .../Resources/Custom/SubscriptionResource.cs | 118 -- .../before/Resources/Custom/TagResource.cs | 70 - .../Resources/Custom/TenantCollection.cs | 28 - .../before/Resources/Custom/TenantResource.cs | 137 -- .../Generated/DataPolicyManifestCollection.cs | 396 ------ .../DataPolicyManifestData.Serialization.cs | 647 --------- .../Generated/DataPolicyManifestData.cs | 117 -- ...ataPolicyManifestResource.Serialization.cs | 29 - .../Generated/DataPolicyManifestResource.cs | 168 --- .../Generated/Extensions/ArmClient.cs | 183 --- .../Generated/Extensions/ArmResource.cs | 156 --- .../Extensions/ManagementGroupResource.cs | 156 --- .../Resources/Generated/FeatureCollection.cs | 394 ------ .../Generated/FeatureData.Serialization.cs | 244 ---- .../before/Resources/Generated/FeatureData.cs | 81 -- .../FeatureResource.Serialization.cs | 29 - .../Resources/Generated/FeatureResource.cs | 316 ----- .../GenericResourceData.Serialization.cs | 609 --------- .../Generated/GenericResourceData.cs | 121 -- .../Internal/Utf8JsonRequestContent.cs | 55 - .../Generated/Internal/WirePathAttribute.cs | 27 - .../GenericResourceOperationSource.cs | 36 - ...esourceGroupExportResultOperationSource.cs | 30 - .../ResourcesArmOperation.cs | 94 -- .../ResourcesArmOperationOfT.cs | 100 -- .../TagResourceOperationSource.cs | 36 - ...nagementGroupPolicyDefinitionCollection.cs | 501 ------- ...pPolicyDefinitionResource.Serialization.cs | 29 - ...ManagementGroupPolicyDefinitionResource.cs | 354 ----- ...ementGroupPolicySetDefinitionCollection.cs | 501 ------- ...licySetDefinitionResource.Serialization.cs | 29 - ...agementGroupPolicySetDefinitionResource.cs | 354 ----- .../Generated/ManagementLockCollection.cs | 488 ------- .../ManagementLockData.Serialization.cs | 334 ----- .../Resources/Generated/ManagementLockData.cs | 94 -- .../ManagementLockResource.Serialization.cs | 29 - .../Generated/ManagementLockResource.cs | 353 ----- .../Models/ApiProfile.Serialization.cs | 204 --- .../Resources/Generated/Models/ApiProfile.cs | 71 - .../ArmPolicyParameter.Serialization.cs | 306 ----- .../Generated/Models/ArmPolicyParameter.cs | 140 -- .../Models/ArmPolicyParameterType.cs | 66 - .../ArmPolicyParameterValue.Serialization.cs | 173 --- .../Models/ArmPolicyParameterValue.cs | 95 -- .../AvailabilityZoneMappings.Serialization.cs | 204 --- .../Models/AvailabilityZoneMappings.cs | 71 - .../AzureRoleDefinition.Serialization.cs | 351 ----- .../Generated/Models/AzureRoleDefinition.cs | 88 -- ...esourceFunctionDefinition.Serialization.cs | 293 ---- ...anifestCustomResourceFunctionDefinition.cs | 83 -- .../DataPolicyManifestEffect.Serialization.cs | 207 --- .../Models/DataPolicyManifestEffect.cs | 100 -- ...aPolicyManifestListResult.Serialization.cs | 219 --- .../Models/DataPolicyManifestListResult.cs | 70 - .../Generated/Models/EnforcementMode.cs | 51 - .../Models/ExportTemplate.Serialization.cs | 154 --- .../Generated/Models/ExportTemplate.cs | 72 - .../Models/ExtendedLocation.Serialization.cs | 194 --- .../Generated/Models/ExtendedLocation.cs | 39 - .../Generated/Models/ExtendedLocationType.cs | 48 - ...atureOperationsListResult.Serialization.cs | 219 --- .../Models/FeatureOperationsListResult.cs | 70 - .../Models/FeatureProperties.Serialization.cs | 170 --- .../Generated/Models/FeatureProperties.cs | 66 - .../Models/LocationExpanded.Serialization.cs | 409 ------ .../Generated/Models/LocationExpanded.cs | 102 -- .../LocationListResult.Serialization.cs | 185 --- .../Generated/Models/LocationListResult.cs | 66 - .../Models/LocationMetadata.Serialization.cs | 443 ------ .../Generated/Models/LocationMetadata.cs | 101 -- .../Models/LocationType.Serialization.cs | 28 - .../Generated/Models/LocationType.cs | 18 - .../Models/ManagedByTenant.Serialization.cs | 166 --- .../Generated/Models/ManagedByTenant.cs | 66 - .../Generated/Models/ManagementLockLevel.cs | 54 - .../ManagementLockListResult.Serialization.cs | 219 --- .../Models/ManagementLockListResult.cs | 70 - .../ManagementLockOwner.Serialization.cs | 170 --- .../Generated/Models/ManagementLockOwner.cs | 66 - .../NonComplianceMessage.Serialization.cs | 201 --- .../Generated/Models/NonComplianceMessage.cs | 81 -- .../Models/PairedRegion.Serialization.cs | 238 ---- .../Generated/Models/PairedRegion.cs | 76 -- ...rDefinitionsValueMetadata.Serialization.cs | 263 ---- .../ParameterDefinitionsValueMetadata.cs | 82 -- .../Models/Permission.Serialization.cs | 381 ------ .../Resources/Generated/Models/Permission.cs | 85 -- ...olicyAssignmentListResult.Serialization.cs | 219 --- .../Models/PolicyAssignmentListResult.cs | 70 - .../PolicyAssignmentPatch.Serialization.cs | 214 --- .../Generated/Models/PolicyAssignmentPatch.cs | 85 -- .../PolicyDefinitionGroup.Serialization.cs | 309 ----- .../Generated/Models/PolicyDefinitionGroup.cs | 96 -- ...olicyDefinitionListResult.Serialization.cs | 219 --- .../Models/PolicyDefinitionListResult.cs | 70 - ...PolicyDefinitionReference.Serialization.cs | 313 ----- .../Models/PolicyDefinitionReference.cs | 93 -- .../Models/PolicyOverride.Serialization.cs | 249 ---- .../Generated/Models/PolicyOverride.cs | 77 -- .../Generated/Models/PolicyOverrideKind.cs | 48 - ...cySetDefinitionListResult.Serialization.cs | 219 --- .../Models/PolicySetDefinitionListResult.cs | 70 - .../Resources/Generated/Models/PolicyType.cs | 57 - .../Models/PredefinedTag.Serialization.cs | 283 ---- .../Generated/Models/PredefinedTag.cs | 82 -- .../PredefinedTagCount.Serialization.cs | 200 --- .../Generated/Models/PredefinedTagCount.cs | 71 - .../PredefinedTagValue.Serialization.cs | 234 ---- .../Generated/Models/PredefinedTagValue.cs | 76 -- .../PredefinedTagsListResult.Serialization.cs | 219 --- .../Models/PredefinedTagsListResult.cs | 70 - .../ProviderAuthorizationConsentState.cs | 57 - ...ProviderConsentDefinition.Serialization.cs | 133 -- .../Models/ProviderConsentDefinition.cs | 66 - .../ProviderExtendedLocation.Serialization.cs | 262 ---- .../Models/ProviderExtendedLocation.cs | 78 -- .../ProviderPermission.Serialization.cs | 260 ---- .../Generated/Models/ProviderPermission.cs | 81 -- ...viderPermissionListResult.Serialization.cs | 219 --- .../Models/ProviderPermissionListResult.cs | 72 - ...oviderRegistrationContent.Serialization.cs | 133 -- .../Models/ProviderRegistrationContent.cs | 77 -- .../ProviderResourceType.Serialization.cs | 627 --------- .../Generated/Models/ProviderResourceType.cs | 118 -- ...derResourceTypeListResult.Serialization.cs | 219 --- .../Models/ProviderResourceTypeListResult.cs | 72 - .../Generated/Models/RegionCategory.cs | 54 - .../Resources/Generated/Models/RegionType.cs | 51 - ...ResourceGroupExportResult.Serialization.cs | 203 --- .../Models/ResourceGroupExportResult.cs | 100 -- .../ResourceGroupListResult.Serialization.cs | 219 --- .../Models/ResourceGroupListResult.cs | 70 - .../ResourceGroupPatch.Serialization.cs | 181 --- .../Generated/Models/ResourceGroupPatch.cs | 88 -- .../ResourceGroupProperties.Serialization.cs | 170 --- .../Models/ResourceGroupProperties.cs | 66 - .../ResourceListResult.Serialization.cs | 219 --- .../Generated/Models/ResourceListResult.cs | 70 - ...urceNameValidationContent.Serialization.cs | 134 -- .../Models/ResourceNameValidationContent.cs | 84 -- ...ourceNameValidationResult.Serialization.cs | 230 ---- .../Models/ResourceNameValidationResult.cs | 77 -- .../Models/ResourceNameValidationStatus.cs | 51 - ...esourceProviderListResult.Serialization.cs | 219 --- .../Models/ResourceProviderListResult.cs | 70 - .../Models/ResourceSelector.Serialization.cs | 219 --- .../Generated/Models/ResourceSelector.cs | 72 - ...esourceSelectorExpression.Serialization.cs | 289 ---- .../Models/ResourceSelectorExpression.cs | 78 -- .../Generated/Models/ResourceSelectorKind.cs | 57 - .../Models/ResourceTypeAlias.Serialization.cs | 350 ----- .../Generated/Models/ResourceTypeAlias.cs | 92 -- .../ResourceTypeAliasPath.Serialization.cs | 292 ---- .../Generated/Models/ResourceTypeAliasPath.cs | 82 -- .../Models/ResourceTypeAliasPathAttributes.cs | 51 - ...urceTypeAliasPathMetadata.Serialization.cs | 196 --- .../Models/ResourceTypeAliasPathMetadata.cs | 71 - .../Models/ResourceTypeAliasPathTokenType.cs | 69 - .../ResourceTypeAliasPattern.Serialization.cs | 234 ---- .../Models/ResourceTypeAliasPattern.cs | 76 -- ...ourceTypeAliasPatternType.Serialization.cs | 28 - .../Models/ResourceTypeAliasPatternType.cs | 18 - .../ResourceTypeAliasType.Serialization.cs | 30 - .../Generated/Models/ResourceTypeAliasType.cs | 20 - .../ResourceTypeAliases.Serialization.cs | 219 --- .../Generated/Models/ResourceTypeAliases.cs | 72 - .../ResourcesMoveContent.Serialization.cs | 158 --- .../Generated/Models/ResourcesMoveContent.cs | 73 - .../Models/ResourcesSku.Serialization.cs | 343 ----- .../Generated/Models/ResourcesSku.cs | 91 -- .../Models/SpendingLimit.Serialization.cs | 30 - .../Generated/Models/SpendingLimit.cs | 20 - .../Resources/Generated/Models/SubResource.cs | 58 - .../SubscriptionListResult.Serialization.cs | 216 --- .../Models/SubscriptionListResult.cs | 80 -- .../SubscriptionPolicies.Serialization.cs | 234 ---- .../Generated/Models/SubscriptionPolicies.cs | 76 -- .../Models/SubscriptionState.Serialization.cs | 34 - .../Generated/Models/SubscriptionState.cs | 24 - .../Generated/Models/Tag.Serialization.cs | 200 --- .../before/Resources/Generated/Models/Tag.cs | 63 - .../Generated/Models/TagPatchMode.cs | 54 - .../Models/TagResourcePatch.Serialization.cs | 148 --- .../Generated/Models/TagResourcePatch.cs | 81 -- .../Models/TenantCategory.Serialization.cs | 30 - .../Generated/Models/TenantCategory.cs | 20 - .../Models/TenantListResult.Serialization.cs | 216 --- .../Generated/Models/TenantListResult.cs | 80 -- .../TenantResourceProvider.Serialization.cs | 219 --- .../Models/TenantResourceProvider.cs | 72 - ...esourceProviderListResult.Serialization.cs | 219 --- .../TenantResourceProviderListResult.cs | 70 - ...ackedResourceExtendedData.Serialization.cs | 313 ----- .../Models/TrackedResourceExtendedData.cs | 80 -- .../Models/ZoneMapping.Serialization.cs | 228 ---- .../Resources/Generated/Models/ZoneMapping.cs | 73 - .../Generated/PolicyAssignmentCollection.cs | 630 --------- .../PolicyAssignmentData.Serialization.cs | 760 ----------- .../Generated/PolicyAssignmentData.cs | 170 --- .../PolicyAssignmentResource.Serialization.cs | 29 - .../Generated/PolicyAssignmentResource.cs | 342 ----- .../PolicyDefinitionData.Serialization.cs | 492 ------- .../Generated/PolicyDefinitionData.cs | 165 --- .../PolicySetDefinitionData.Serialization.cs | 517 ------- .../Generated/PolicySetDefinitionData.cs | 138 -- .../Generated/ResourceGroupCollection.cs | 500 ------- .../ResourceGroupData.Serialization.cs | 352 ----- .../Resources/Generated/ResourceGroupData.cs | 95 -- .../ResourceGroupResource.Serialization.cs | 29 - .../Generated/ResourceGroupResource.cs | 980 -------------- .../Generated/ResourceManagerModelFactory.cs | 764 ----------- .../Generated/ResourceProviderCollection.cs | 389 ------ .../ResourceProviderData.Serialization.cs | 355 ----- .../Generated/ResourceProviderData.cs | 87 -- .../ResourceProviderResource.Serialization.cs | 29 - .../Generated/ResourceProviderResource.cs | 509 ------- .../DataPolicyManifestsRestOperations.cs | 265 ---- .../RestOperations/FeaturesRestOperations.cs | 643 --------- .../ManagementLocksRestOperations.cs | 459 ------- .../PolicyAssignmentsRestOperations.cs | 1183 ----------------- .../PolicyDefinitionsRestOperations.cs | 1145 ---------------- .../PolicySetDefinitionsRestOperations.cs | 1149 ---------------- .../ProviderResourceTypesRestOperations.cs | 135 -- .../RestOperations/ProvidersRestOperations.cs | 802 ----------- .../ResourceGroupsRestOperations.cs | 663 --------- .../ResourceManagementRestOperations.cs | 112 -- .../RestOperations/ResourcesRestOperations.cs | 915 ------------- .../SubscriptionsRestOperations.cs | 341 ----- .../RestOperations/TagsRestOperations.cs | 833 ------------ .../RestOperations/TenantsRestOperations.cs | 182 --- .../Generated/SubscriptionCollection.cs | 394 ------ .../SubscriptionData.Serialization.cs | 481 ------- .../Resources/Generated/SubscriptionData.cs | 109 -- .../SubscriptionPolicyDefinitionCollection.cs | 500 ------- ...nPolicyDefinitionResource.Serialization.cs | 29 - .../SubscriptionPolicyDefinitionResource.cs | 353 ----- ...bscriptionPolicySetDefinitionCollection.cs | 500 ------- ...licySetDefinitionResource.Serialization.cs | 29 - ...SubscriptionPolicySetDefinitionResource.cs | 353 ----- .../SubscriptionResource.Serialization.cs | 29 - .../Generated/SubscriptionResource.cs | 962 -------------- .../Generated/TagResource.Serialization.cs | 29 - .../before/Resources/Generated/TagResource.cs | 437 ------ .../TagResourceData.Serialization.cs | 237 ---- .../Resources/Generated/TagResourceData.cs | 96 -- .../Resources/Generated/TenantCollection.cs | 199 --- .../Generated/TenantData.Serialization.cs | 504 ------- .../before/Resources/Generated/TenantData.cs | 116 -- .../TenantPolicyDefinitionCollection.cs | 398 ------ ...tPolicyDefinitionResource.Serialization.cs | 29 - .../TenantPolicyDefinitionResource.cs | 168 --- .../TenantPolicySetDefinitionCollection.cs | 398 ------ ...licySetDefinitionResource.Serialization.cs | 29 - .../TenantPolicySetDefinitionResource.cs | 168 --- .../Generated/TenantResource.Serialization.cs | 29 - .../Resources/Generated/TenantResource.cs | 505 ------- .../before/Shared/AppContextSwitchHelper.cs | 42 - .../before/Shared/AsyncLockWithValue.cs | 260 ---- ...AzureResourceProviderNamespaceAttribute.cs | 22 - .../before/Shared/ClientDiagnostics.cs | 73 - .../before/Shared/DiagnosticScope.cs | 448 ------- .../before/Shared/DiagnosticScopeFactory.cs | 103 -- .../Shared/FixedDelayWithNoJitterStrategy.cs | 26 - .../Shared/ForwardsClientCallsAttribute.cs | 39 - .../before/Shared/HashCodeBuilder.cs | 387 ------ .../before/Shared/HttpMessageSanitizer.cs | 198 --- .../before/Shared/HttpPipelineExtensions.cs | 110 -- .../before/Shared/IOperationSource.cs | 14 - .../before/Shared/IUtf8JsonSerializable.cs | 14 - .../InitializationConstructorAttribute.cs | 15 - .../ManagedServiceIdentityTypeV3Converter.cs | 53 - .../Shared/NextLinkOperationImplementation.cs | 701 ---------- .../before/Shared/NoValueResponseOfT.cs | 39 - .../before/Shared/OperationFinalStateVia.cs | 16 - .../before/Shared/OperationInternal.cs | 263 ---- .../before/Shared/OperationInternalBase.cs | 234 ---- .../before/Shared/OperationInternalOfT.cs | 431 ------ .../before/Shared/OperationPoller.cs | 114 -- .../dotnet-aot-compat/before/Shared/Page.cs | 16 - .../before/Shared/PageableHelpers.cs | 556 -------- .../Shared/PropertyReferenceTypeAttribute.cs | 52 - .../before/Shared/ProtocolOperation.cs | 78 -- .../before/Shared/RawRequestUriBuilder.cs | 229 ---- .../before/Shared/ReferenceTypeAttribute.cs | 36 - .../before/Shared/SequentialDelayStrategy.cs | 38 - .../SerializationConstructorAttribute.cs | 15 - .../before/Shared/SharedExtensions.cs | 82 -- .../before/Shared/TaskExtensions.cs | 313 ----- .../before/Shared/TypeFormatters.cs | 159 --- .../Shared/TypeReferenceTypeAttribute.cs | 41 - .../before/Shared/VoidValue.cs | 10 - .../dotnet-aot-compat/before/autorest.md | 839 ------------ .../dotnet-aot-compat/before/global.json | 6 - .../dotnet-aot-compat/eval.yaml | 33 - .../migrate-dotnet9-to-dotnet10/eval.yaml | 767 ----------- 1031 files changed, 169029 deletions(-) delete mode 100644 plugins/dotnet-blazor/skills/plan-ui-change/SKILL.md delete mode 100644 plugins/dotnet-blazor/skills/support-prerendering/SKILL.md delete mode 100644 plugins/dotnet-diag/skills/android-tombstone-symbolication/SKILL.md delete mode 100644 plugins/dotnet-diag/skills/android-tombstone-symbolication/scripts/Symbolicate-Tombstone.ps1 delete mode 100644 plugins/dotnet-diag/skills/microbenchmarking/SKILL.md delete mode 100644 plugins/dotnet-diag/skills/microbenchmarking/references/bdn-internals-and-tuning.md delete mode 100644 plugins/dotnet-diag/skills/microbenchmarking/references/comparison-strategies.md delete mode 100644 plugins/dotnet-diag/skills/microbenchmarking/references/diagnosers-and-exporters.md delete mode 100644 plugins/dotnet-diag/skills/microbenchmarking/references/project-setup-and-running.md delete mode 100644 plugins/dotnet-diag/skills/microbenchmarking/references/writing-benchmarks.md delete mode 100644 plugins/dotnet-maui/skills/maui-collectionview/SKILL.md delete mode 100644 plugins/dotnet-maui/skills/maui-collectionview/references/collectionview-api.md delete mode 100644 plugins/dotnet-msbuild/skills/check-bin-obj-clash/SKILL.md delete mode 100644 plugins/dotnet-msbuild/skills/eval-performance/SKILL.md delete mode 100644 plugins/dotnet-msbuild/skills/msbuild-antipatterns/SKILL.md delete mode 100644 plugins/dotnet-msbuild/skills/msbuild-antipatterns/references/additional-antipatterns.md delete mode 100644 plugins/dotnet-msbuild/skills/msbuild-antipatterns/references/incremental-build-inputs-outputs.md delete mode 100644 plugins/dotnet-msbuild/skills/msbuild-antipatterns/references/private-assets.md delete mode 100644 plugins/dotnet-test/skills/migrate-static-to-wrapper/SKILL.md delete mode 100644 plugins/dotnet-upgrade/skills/dotnet-aot-compat/SKILL.md delete mode 100644 plugins/dotnet-upgrade/skills/dotnet-aot-compat/references/polyfills.md delete mode 100644 plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/SKILL.md delete mode 100644 plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/aspnet-core-dotnet9to10.md delete mode 100644 plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/containers-interop-dotnet9to10.md delete mode 100644 plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/core-libraries-dotnet9to10.md delete mode 100644 plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/cryptography-dotnet9to10.md delete mode 100644 plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/csharp-compiler-dotnet9to10.md delete mode 100644 plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/efcore-dotnet9to10.md delete mode 100644 plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/extensions-hosting-dotnet9to10.md delete mode 100644 plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/sdk-msbuild-dotnet9to10.md delete mode 100644 plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/serialization-networking-dotnet9to10.md delete mode 100644 plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/winforms-wpf-dotnet9to10.md delete mode 100644 tests/dotnet-blazor/plan-ui-change/eval.yaml delete mode 100644 tests/dotnet-blazor/support-prerendering/eval.yaml delete mode 100644 tests/dotnet-diag/android-tombstone-symbolication/crashlog_ios.txt delete mode 100644 tests/dotnet-diag/android-tombstone-symbolication/eval.yaml delete mode 100644 tests/dotnet-diag/android-tombstone-symbolication/tombstone_coreclr.txt delete mode 100644 tests/dotnet-diag/android-tombstone-symbolication/tombstone_multi_buildid.txt delete mode 100644 tests/dotnet-diag/android-tombstone-symbolication/tombstone_multithread.txt delete mode 100644 tests/dotnet-diag/android-tombstone-symbolication/tombstone_nativeaot.txt delete mode 100644 tests/dotnet-diag/android-tombstone-symbolication/tombstone_no_buildid.txt delete mode 100644 tests/dotnet-diag/android-tombstone-symbolication/tombstone_no_dotnet.txt delete mode 100644 tests/dotnet-diag/android-tombstone-symbolication/tombstone_sample.txt delete mode 100644 tests/dotnet-diag/microbenchmarking/TextAnalyzer/TextAnalyzer.cs delete mode 100644 tests/dotnet-diag/microbenchmarking/TextAnalyzer/TextAnalyzer.csproj delete mode 100644 tests/dotnet-diag/microbenchmarking/eval.yaml delete mode 100644 tests/dotnet-maui/maui-collectionview/eval.yaml delete mode 100644 tests/dotnet-msbuild/check-bin-obj-clash/.gitignore delete mode 100644 tests/dotnet-msbuild/check-bin-obj-clash/ClashTest.slnx delete mode 100644 tests/dotnet-msbuild/check-bin-obj-clash/ConsumerApp/Consumer.cs delete mode 100644 tests/dotnet-msbuild/check-bin-obj-clash/ConsumerApp/ConsumerApp.csproj delete mode 100644 tests/dotnet-msbuild/check-bin-obj-clash/LibraryA/ClassA.cs delete mode 100644 tests/dotnet-msbuild/check-bin-obj-clash/LibraryA/LibraryA.csproj delete mode 100644 tests/dotnet-msbuild/check-bin-obj-clash/LibraryB/ClassB.cs delete mode 100644 tests/dotnet-msbuild/check-bin-obj-clash/LibraryB/LibraryB.csproj delete mode 100644 tests/dotnet-msbuild/check-bin-obj-clash/MultiTargetLib/MultiClass.cs delete mode 100644 tests/dotnet-msbuild/check-bin-obj-clash/MultiTargetLib/MultiTargetLib.csproj delete mode 100644 tests/dotnet-msbuild/check-bin-obj-clash/ToolLib/Tool.cs delete mode 100644 tests/dotnet-msbuild/check-bin-obj-clash/ToolLib/ToolLib.csproj delete mode 100644 tests/dotnet-msbuild/check-bin-obj-clash/eval.yaml delete mode 100644 tests/dotnet-msbuild/eval-performance/EvalHeavy.csproj delete mode 100644 tests/dotnet-msbuild/eval-performance/Program.cs delete mode 100644 tests/dotnet-msbuild/eval-performance/build-notes.txt delete mode 100644 tests/dotnet-msbuild/eval-performance/eval.yaml delete mode 100644 tests/dotnet-msbuild/eval-performance/imports/level1.props delete mode 100644 tests/dotnet-msbuild/eval-performance/imports/level2.props delete mode 100644 tests/dotnet-msbuild/eval-performance/imports/level3.props delete mode 100644 tests/dotnet-msbuild/msbuild-antipatterns/Directory.Build.props delete mode 100644 tests/dotnet-msbuild/msbuild-antipatterns/Directory.Build.targets delete mode 100644 tests/dotnet-msbuild/msbuild-antipatterns/LibA/Class1.cs delete mode 100644 tests/dotnet-msbuild/msbuild-antipatterns/LibA/LibA.csproj delete mode 100644 tests/dotnet-msbuild/msbuild-antipatterns/LibB/Class2.cs delete mode 100644 tests/dotnet-msbuild/msbuild-antipatterns/LibB/LibB.csproj delete mode 100644 tests/dotnet-msbuild/msbuild-antipatterns/StyleIssues.sln delete mode 100644 tests/dotnet-msbuild/msbuild-antipatterns/eval.yaml delete mode 100644 tests/dotnet-msbuild/msbuild-antipatterns/fsharp/BrokenOrder/BrokenOrder.fsproj delete mode 100644 tests/dotnet-msbuild/msbuild-antipatterns/fsharp/BrokenOrder/Domain.fs delete mode 100644 tests/dotnet-msbuild/msbuild-antipatterns/fsharp/BrokenOrder/Program.fs delete mode 100644 tests/dotnet-msbuild/msbuild-antipatterns/fsharp/BrokenOrder/Services.fs delete mode 100644 tests/dotnet-msbuild/msbuild-antipatterns/fsharp/Directory.Build.props delete mode 100644 tests/dotnet-msbuild/msbuild-antipatterns/fsharp/Directory.Build.targets delete mode 100644 tests/dotnet-msbuild/msbuild-antipatterns/fsharp/OrderService/Domain.fs delete mode 100644 tests/dotnet-msbuild/msbuild-antipatterns/fsharp/OrderService/OrderService.fsproj delete mode 100644 tests/dotnet-msbuild/msbuild-antipatterns/fsharp/OrderService/Program.fs delete mode 100644 tests/dotnet-msbuild/msbuild-antipatterns/fsharp/OrderService/Services.fs delete mode 100644 tests/dotnet-test/migrate-static-to-wrapper/eval.yaml delete mode 100644 tests/dotnet-test/migrate-static-to-wrapper/fixtures/decline-no-wrapper/DataLoader.cs delete mode 100644 tests/dotnet-test/migrate-static-to-wrapper/fixtures/decline-no-wrapper/MyProject.csproj delete mode 100644 tests/dotnet-test/migrate-static-to-wrapper/fixtures/ready-to-migrate/Program.cs delete mode 100644 tests/dotnet-test/migrate-static-to-wrapper/fixtures/ready-to-migrate/ReadyToMigrate.csproj delete mode 100644 tests/dotnet-test/migrate-static-to-wrapper/fixtures/ready-to-migrate/Services/AuditLogger.cs delete mode 100644 tests/dotnet-test/migrate-static-to-wrapper/fixtures/ready-to-migrate/Services/CouponService.cs delete mode 100644 tests/dotnet-test/migrate-static-to-wrapper/fixtures/static-helper/StaticHelper.csproj delete mode 100644 tests/dotnet-test/migrate-static-to-wrapper/fixtures/static-helper/Utilities/RetentionPolicy.cs delete mode 100644 tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing.Tests/Billing.Tests.csproj delete mode 100644 tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing.Tests/SubscriptionServiceTests.cs delete mode 100644 tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Abstractions/IClock.cs delete mode 100644 tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Abstractions/SystemClock.cs delete mode 100644 tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Billing.csproj delete mode 100644 tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Services/InvoiceService.cs delete mode 100644 tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Services/SubscriptionService.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/.gitignore delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ArmClient.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ArmClientOptions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ArmCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ArmEnvironment.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ArmOperation.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ArmOperationOfT.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ArmResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Assets/Profile/2020-09-01-hybrid.json delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Azure.ResourceManager.csproj delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/AzureStackProfile.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/BicepModelReaderWriterOptions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/CodeGenAttributes.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ArmPlan.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ArmSku.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/EncryptionProperties.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/EncryptionStatus.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/KeyVaultProperties.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentity.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentity.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentityType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/SystemAssignedServiceIdentity.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/SystemAssignedServiceIdentityType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/ResourceManagerModelFactory.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/Argument.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/BicepSerializationHelpers.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/ChangeTrackingDictionary.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/ChangeTrackingList.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/ModelSerializationExtensions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/Optional.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/WirePathAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmPlan.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmPlan.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmSku.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmSku.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmSkuTier.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmSkuTier.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/AzureResourceManagerContext.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/CreatedByType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/EncryptionProperties.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/EncryptionProperties.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/EncryptionStatus.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/KeyVaultProperties.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/KeyVaultProperties.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ManagedServiceIdentityType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/OperationStatusResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/OperationStatusResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ResourceData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ResourceData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentity.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentity.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentityType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/TrackedResourceData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/TrackedResourceData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/UserAssignedIdentity.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/UserAssignedIdentity.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Directory.Build.props delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Directory.Packages.props delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ExperimentalAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Extensions/ArmClientBuilderExtensions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/GenericOperationSource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Custom/HelperSuppressions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Custom/ManagementGroupResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Custom/Models/ManagementGroupNameAvailabilityContent.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Extensions/ArmClient.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Extensions/TenantResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Internal/WirePathAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupOperationSource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperation.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperationOfT.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/CreateManagementGroupDetails.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/CreateManagementGroupDetails.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantParentGroupInfo.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantParentGroupInfo.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityPermission.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityPermission.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntitySearchOption.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityViewOption.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildInfo.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildInfo.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildOptions.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildOptions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCollectionGetEntitiesOptions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupExpandType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupInfo.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupInfo.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPatch.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPatch.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPathElement.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPathElement.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ParentManagementGroupInfo.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ParentManagementGroupInfo.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ResourceManagerModelFactory.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/EntitiesRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/ManagementGroupSubscriptionsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/ManagementGroupsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Properties/AssemblyInfo.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ProviderConstants.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/RehydrationOperation.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/RehydrationOperationOfT.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ResourceManagerExtensions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/ResourceManagerJsonContext.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ArmClient.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ArmRestApiCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Extensions/ArmResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/FeatureResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/GenericResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/GenericResourceCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/GenericResourceData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/HelperSuppressions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApi.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApi.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApiListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApiListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/EnforcementMode.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/LocationExpanded.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/LocationMetadata.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ResourcesMoveContent.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ResourcesSku.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/SubResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/SubResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/Tag.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/WritableSubResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/WritableSubResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/PolicyAssignmentData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/PolicyAssignmentResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceGroupBuilder.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceGroupCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceGroupResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceManagerModelFactory.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceProviderCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceProviderData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceProviderResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/RestOperations/RestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/RestOperations/TenantsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/SubscriptionData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/SubscriptionResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/TagResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/TenantCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/TenantResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Extensions/ArmClient.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Extensions/ArmResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Extensions/ManagementGroupResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/GenericResourceData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/GenericResourceData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Internal/Utf8JsonRequestContent.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Internal/WirePathAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/GenericResourceOperationSource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourceGroupExportResultOperationSource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourcesArmOperation.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourcesArmOperationOfT.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/TagResourceOperationSource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ApiProfile.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ApiProfile.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameter.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameter.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterValue.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterValue.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/AvailabilityZoneMappings.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/AvailabilityZoneMappings.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/AzureRoleDefinition.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/AzureRoleDefinition.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestEffect.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestEffect.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/EnforcementMode.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExportTemplate.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExportTemplate.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocation.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocation.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocationType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/FeatureOperationsListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/FeatureOperationsListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/FeatureProperties.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/FeatureProperties.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationExpanded.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationExpanded.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationMetadata.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationMetadata.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationType.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagedByTenant.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagedByTenant.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockLevel.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockOwner.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockOwner.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/NonComplianceMessage.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/NonComplianceMessage.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PairedRegion.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PairedRegion.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ParameterDefinitionsValueMetadata.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ParameterDefinitionsValueMetadata.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/Permission.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/Permission.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentPatch.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentPatch.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionGroup.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionGroup.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionReference.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionReference.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverride.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverride.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverrideKind.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicySetDefinitionListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicySetDefinitionListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTag.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTag.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagCount.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagCount.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagValue.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagValue.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagsListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagsListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderAuthorizationConsentState.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderConsentDefinition.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderConsentDefinition.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderExtendedLocation.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderExtendedLocation.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermission.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermission.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermissionListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermissionListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderRegistrationContent.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderRegistrationContent.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceType.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceTypeListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceTypeListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/RegionCategory.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/RegionType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupExportResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupExportResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupPatch.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupPatch.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupProperties.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupProperties.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationContent.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationContent.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationStatus.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceProviderListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceProviderListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelector.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelector.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorExpression.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorExpression.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorKind.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAlias.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAlias.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPath.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPath.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathAttributes.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathMetadata.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathMetadata.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathTokenType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPattern.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPattern.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPatternType.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPatternType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasType.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliases.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliases.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesMoveContent.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesMoveContent.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesSku.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesSku.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SpendingLimit.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SpendingLimit.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionPolicies.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionPolicies.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionState.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionState.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/Tag.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/Tag.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TagPatchMode.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TagResourcePatch.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TagResourcePatch.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantCategory.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantCategory.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProvider.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProvider.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProviderListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProviderListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TrackedResourceExtendedData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TrackedResourceExtendedData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ZoneMapping.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ZoneMapping.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyDefinitionData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyDefinitionData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicySetDefinitionData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicySetDefinitionData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceManagerModelFactory.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/DataPolicyManifestsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/FeaturesRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ManagementLocksRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicyAssignmentsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicyDefinitionsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicySetDefinitionsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ProviderResourceTypesRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ProvidersRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourceGroupsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourceManagementRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourcesRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/SubscriptionsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/TagsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/TenantsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TagResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TagResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TagResourceData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TagResourceData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/AppContextSwitchHelper.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/AsyncLockWithValue.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/AzureResourceProviderNamespaceAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ClientDiagnostics.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/DiagnosticScope.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/DiagnosticScopeFactory.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/FixedDelayWithNoJitterStrategy.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ForwardsClientCallsAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/HashCodeBuilder.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/HttpMessageSanitizer.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/HttpPipelineExtensions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/IOperationSource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/IUtf8JsonSerializable.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/InitializationConstructorAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ManagedServiceIdentityTypeV3Converter.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/NextLinkOperationImplementation.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/NoValueResponseOfT.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationFinalStateVia.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationInternal.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationInternalBase.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationInternalOfT.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationPoller.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/Page.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/PageableHelpers.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/PropertyReferenceTypeAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ProtocolOperation.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/RawRequestUriBuilder.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ReferenceTypeAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ResponseErrorConverter.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/SequentialDelayStrategy.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/SerializationConstructorAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/SharedExtensions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/TaskExtensions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/TypeFormatters.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/TypeReferenceTypeAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/VoidValue.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/autorest.md delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/after/global.json delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/.gitignore delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ArmClient.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ArmClientOptions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ArmCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ArmEnvironment.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ArmOperation.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ArmOperationOfT.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ArmResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Assets/Profile/2020-09-01-hybrid.json delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Azure.ResourceManager.csproj delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/AzureStackProfile.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/BicepModelReaderWriterOptions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/CodeGenAttributes.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ArmPlan.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ArmSku.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/EncryptionProperties.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/EncryptionStatus.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/KeyVaultProperties.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentity.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentity.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentityType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/SystemAssignedServiceIdentity.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/SystemAssignedServiceIdentityType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/ResourceManagerModelFactory.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/Argument.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/BicepSerializationHelpers.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/ChangeTrackingDictionary.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/ChangeTrackingList.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/ModelSerializationExtensions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/Optional.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/WirePathAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmPlan.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmPlan.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmSku.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmSku.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmSkuTier.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmSkuTier.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/AzureResourceManagerContext.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/CreatedByType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/EncryptionProperties.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/EncryptionProperties.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/EncryptionStatus.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/KeyVaultProperties.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/KeyVaultProperties.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ManagedServiceIdentityType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/OperationStatusResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/OperationStatusResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ResourceData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ResourceData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentity.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentity.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentityType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/TrackedResourceData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/TrackedResourceData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/UserAssignedIdentity.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/UserAssignedIdentity.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Directory.Build.props delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Directory.Packages.props delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ExperimentalAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Extensions/ArmClientBuilderExtensions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/GenericOperationSource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Custom/HelperSuppressions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Custom/ManagementGroupResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Custom/Models/ManagementGroupNameAvailabilityContent.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Extensions/ArmClient.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Extensions/TenantResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Internal/WirePathAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupOperationSource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperation.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperationOfT.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/CreateManagementGroupDetails.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/CreateManagementGroupDetails.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantParentGroupInfo.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantParentGroupInfo.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityPermission.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityPermission.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntitySearchOption.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityViewOption.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildInfo.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildInfo.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildOptions.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildOptions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCollectionGetEntitiesOptions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupExpandType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupInfo.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupInfo.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPatch.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPatch.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPathElement.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPathElement.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ParentManagementGroupInfo.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ParentManagementGroupInfo.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ResourceManagerModelFactory.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/EntitiesRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/ManagementGroupSubscriptionsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/ManagementGroupsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Properties/AssemblyInfo.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ProviderConstants.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/RehydrationOperation.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/RehydrationOperationOfT.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/ResourceManagerExtensions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ArmClient.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ArmRestApiCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Extensions/ArmResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/FeatureResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/GenericResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/GenericResourceCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/GenericResourceData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/HelperSuppressions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApi.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApi.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApiListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApiListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/EnforcementMode.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/LocationExpanded.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/LocationMetadata.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ResourcesMoveContent.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ResourcesSku.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/SubResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/SubResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/Tag.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/WritableSubResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/WritableSubResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/PolicyAssignmentData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/PolicyAssignmentResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceGroupBuilder.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceGroupCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceGroupResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceManagerModelFactory.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceProviderCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceProviderData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceProviderResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/RestOperations/RestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/RestOperations/TenantsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/SubscriptionData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/SubscriptionResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/TagResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/TenantCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/TenantResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Extensions/ArmClient.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Extensions/ArmResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Extensions/ManagementGroupResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/GenericResourceData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/GenericResourceData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Internal/Utf8JsonRequestContent.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Internal/WirePathAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/GenericResourceOperationSource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourceGroupExportResultOperationSource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourcesArmOperation.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourcesArmOperationOfT.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/TagResourceOperationSource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ApiProfile.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ApiProfile.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameter.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameter.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterValue.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterValue.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/AvailabilityZoneMappings.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/AvailabilityZoneMappings.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/AzureRoleDefinition.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/AzureRoleDefinition.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestEffect.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestEffect.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/EnforcementMode.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExportTemplate.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExportTemplate.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocation.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocation.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocationType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/FeatureOperationsListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/FeatureOperationsListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/FeatureProperties.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/FeatureProperties.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationExpanded.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationExpanded.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationMetadata.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationMetadata.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationType.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagedByTenant.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagedByTenant.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockLevel.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockOwner.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockOwner.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/NonComplianceMessage.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/NonComplianceMessage.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PairedRegion.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PairedRegion.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ParameterDefinitionsValueMetadata.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ParameterDefinitionsValueMetadata.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/Permission.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/Permission.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentPatch.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentPatch.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionGroup.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionGroup.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionReference.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionReference.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverride.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverride.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverrideKind.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicySetDefinitionListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicySetDefinitionListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTag.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTag.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagCount.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagCount.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagValue.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagValue.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagsListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagsListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderAuthorizationConsentState.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderConsentDefinition.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderConsentDefinition.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderExtendedLocation.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderExtendedLocation.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermission.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermission.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermissionListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermissionListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderRegistrationContent.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderRegistrationContent.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceType.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceTypeListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceTypeListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/RegionCategory.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/RegionType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupExportResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupExportResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupPatch.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupPatch.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupProperties.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupProperties.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationContent.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationContent.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationStatus.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceProviderListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceProviderListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelector.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelector.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorExpression.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorExpression.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorKind.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAlias.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAlias.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPath.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPath.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathAttributes.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathMetadata.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathMetadata.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathTokenType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPattern.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPattern.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPatternType.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPatternType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasType.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasType.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliases.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliases.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesMoveContent.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesMoveContent.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesSku.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesSku.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SpendingLimit.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SpendingLimit.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionPolicies.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionPolicies.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionState.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionState.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/Tag.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/Tag.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TagPatchMode.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TagResourcePatch.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TagResourcePatch.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantCategory.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantCategory.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProvider.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProvider.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProviderListResult.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProviderListResult.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TrackedResourceExtendedData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TrackedResourceExtendedData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ZoneMapping.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ZoneMapping.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyDefinitionData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyDefinitionData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicySetDefinitionData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicySetDefinitionData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceManagerModelFactory.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/DataPolicyManifestsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/FeaturesRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ManagementLocksRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicyAssignmentsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicyDefinitionsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicySetDefinitionsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ProviderResourceTypesRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ProvidersRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourceGroupsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourceManagementRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourcesRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/SubscriptionsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/TagsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/TenantsRestOperations.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TagResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TagResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TagResourceData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TagResourceData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantData.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantData.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionCollection.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantResource.Serialization.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantResource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/AppContextSwitchHelper.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/AsyncLockWithValue.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/AzureResourceProviderNamespaceAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ClientDiagnostics.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/DiagnosticScope.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/DiagnosticScopeFactory.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/FixedDelayWithNoJitterStrategy.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ForwardsClientCallsAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/HashCodeBuilder.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/HttpMessageSanitizer.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/HttpPipelineExtensions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/IOperationSource.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/IUtf8JsonSerializable.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/InitializationConstructorAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ManagedServiceIdentityTypeV3Converter.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/NextLinkOperationImplementation.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/NoValueResponseOfT.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationFinalStateVia.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationInternal.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationInternalBase.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationInternalOfT.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationPoller.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/Page.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/PageableHelpers.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/PropertyReferenceTypeAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ProtocolOperation.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/RawRequestUriBuilder.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ReferenceTypeAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/SequentialDelayStrategy.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/SerializationConstructorAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/SharedExtensions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/TaskExtensions.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/TypeFormatters.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/TypeReferenceTypeAttribute.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/VoidValue.cs delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/autorest.md delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/before/global.json delete mode 100644 tests/dotnet-upgrade/dotnet-aot-compat/eval.yaml delete mode 100644 tests/dotnet-upgrade/migrate-dotnet9-to-dotnet10/eval.yaml diff --git a/plugins/dotnet-blazor/skills/plan-ui-change/SKILL.md b/plugins/dotnet-blazor/skills/plan-ui-change/SKILL.md deleted file mode 100644 index 541736ae90..0000000000 --- a/plugins/dotnet-blazor/skills/plan-ui-change/SKILL.md +++ /dev/null @@ -1,152 +0,0 @@ ---- -license: MIT -name: plan-ui-change -description: > - Plan complex Blazor UI features by decomposing them into focused components. - USE FOR: building a complex Blazor page with multiple sections, planning - component decomposition, designing a multi-section dashboard or layout, - breaking down a large UI feature into composable components, pages with - sidebars and content panels, any page with 3+ distinct visual sections - or multiple interacting sub-features, identifying parent-child relationships - and data flow. - DO NOT USE FOR: creating new Blazor projects or apps from scratch - (use create-blazor-project), implementing a single individual component - (use author-component), writing component code with parameters and - EventCallback (use author-component), or simple single-component pages. ---- - -# Plan a Blazor UI Change - -When asked to build a complex UI feature, **plan the component decomposition first, then immediately implement it**. A single monolithic page component is almost never the right answer — break the UI into focused, composable components. - -## Planning Workflow - -### Step 1 — Map the Visual Regions - -Read the request and identify every distinct visual region. Each region that has its own data, behavior, or layout responsibility is a candidate component. - -Draw the component tree: - -``` -InventoryDashboard (page — owns data, orchestrates layout) -├── StockSummaryBar (read-only stats: total items, low-stock count, value) -├── InventoryFilters (search box, category dropdown, stock-level toggle) -├── InventoryTable (sortable table of products) -│ └── InventoryRow (single product row with inline edit/delete) -└── AddProductForm (slide-out form for new products) -``` - -Rules for identifying components: -- **Distinct responsibility** — a region owns its own state or behavior → separate component -- **Repeated structure** — items in a list, cards in a grid → extract the item template -- **Independent interactivity** — a section that handles user input separately from its siblings → separate component -- **Size** — any section that would exceed ~150 lines of markup on its own → split it - -### Step 2 — Classify Each Component - -For every component in the tree, determine: - -| Component | Action | Render Mode | State Owned | Lines (est.) | -|-----------|--------|-------------|-------------|-------------| -| InventoryDashboard | Create | InteractiveServer | product list, filter state | ~80 | -| StockSummaryBar | Create | (inherits) | none — receives data | ~30 | -| InventoryFilters | Create | (inherits) | search text, selected category | ~60 | -| InventoryTable | Create | (inherits) | sort column, sort direction | ~50 | -| InventoryRow | Create | (inherits) | inline-edit mode flag | ~60 | -| AddProductForm | Create | (inherits) | form model | ~80 | - -**A page component that exceeds ~200 lines of combined markup + code is too large.** If your estimate puts a single component above that, split further. - -### Step 3 — Design Data Flow - -Identify the **state owner** for each piece of data, then map how it flows: - -``` -InventoryDashboard (owns: products[], filters) - │ - ├─ [Parameter] products ──→ StockSummaryBar (reads aggregate stats) - │ - ├─ [Parameter] filters ──→ InventoryFilters - │ └─ EventCallback OnFiltersChanged ──→ InventoryDashboard - │ - ├─ [Parameter] filteredProducts ──→ InventoryTable - │ └─ [Parameter] product ──→ InventoryRow - │ ├─ EventCallback OnSave ──→ InventoryTable ──→ InventoryDashboard - │ └─ EventCallback OnDelete ──→ InventoryTable ──→ InventoryDashboard - │ - └─ EventCallback OnProductAdded ←── AddProductForm -``` - -Rules: -- Data always flows **down** through `[Parameter]` -- Events always flow **up** through `EventCallback` -- The page/parent **owns the data** and passes filtered/transformed views to children -- Children **never mutate parameters** — they notify the parent via callbacks -- If data must cross more than 2 levels without intermediate components needing it, use a cascading value or a scoped service - -### Step 4 — Identify Reuse Opportunities - -Before creating a new component, check if an existing component in the project can serve the purpose. Look for: -- Existing list-item components that match the structure -- Shared filter/search components already in the project -- Generic components (e.g., `DataTable`, `Pagination`) that accept templates - -If a component will be used in more than one page, place it in a `Shared/` or `Components/` folder. - -### Step 5 — Order the Implementation - -Build bottom-up — leaf components first, then parents that compose them: - -1. **Models/DTOs** — define the data shapes -2. **Services** — data access, business logic (interface + implementation) -3. **Leaf components** — components with no children (InventoryRow, StockSummaryBar) -4. **Container components** — components that compose leaves (InventoryTable, InventoryFilters) -5. **Page component** — wires everything together, registers routes -6. **Configuration** — DI registration, render mode setup - -Each component should be independently compilable. Never reference a component that doesn't exist yet. - -## Output Format - -Present the plan briefly, then **immediately proceed to implement** — never stop at just the plan or ask for confirmation before writing code. The plan is a thinking tool, not a deliverable. - -```markdown -## Component Plan: [Feature Name] - -### Component Tree -[ASCII tree showing parent-child relationships] - -### Component Table -| Component | Action | Render Mode | Purpose | Est. Lines | -|-----------|--------|-------------|---------|------------| -| ... | ... | ... | ... | ... | - -### Data Flow -[State owner] → [Parameters down] → [EventCallbacks up] - -### Implementation Order -1. [First file to create — why] -2. [Second file — why] -... -``` - -After outputting the plan, **immediately begin implementing** the components in the order listed. Do not wait for approval or ask "shall I proceed?" — the plan is a guide for you to follow, not a proposal for the user to approve. - -## Anti-Patterns to Avoid - -| Anti-Pattern | Why It's Wrong | Correct Approach | -|-------------|----------------|-----------------| -| One page component with 500+ lines | Impossible to test, reuse, or maintain | Decompose into focused components | -| Passing 10+ parameters through intermediate components | Parameter drilling obscures intent | Use cascading values or a scoped state service | -| Child component fetching its own data from an API | Multiple components making redundant calls | Parent owns data, passes via parameters | -| Inline rendering of list items with complex markup | Duplicated logic, no reuse, hard to test | Extract item template into its own component | -| Building everything in one file then "refactoring later" | Refactoring rarely happens; the monolith ships | Plan the decomposition upfront | -| Generic components for one-off usage | Over-engineering adds complexity | Only extract generics when reuse is proven | - -## Guidelines - -- **Plan briefly, then implement.** Write a concise component table and data flow map, then immediately create the `.razor` files — never stop at just the plan. -- **Prefer many small components over one large one.** A component with a single clear purpose is easier to understand, test, and reuse. -- **State ownership is the first decision.** Before writing fetch logic, decide which component owns the data. -- **Build bottom-up.** Create leaf components first so parent components can reference them immediately. -- **Name components after what they render**, not what they do internally: `ProductCard` not `ProductRenderer`, `OrderFilters` not `FilterHandler`. diff --git a/plugins/dotnet-blazor/skills/support-prerendering/SKILL.md b/plugins/dotnet-blazor/skills/support-prerendering/SKILL.md deleted file mode 100644 index 33495a887d..0000000000 --- a/plugins/dotnet-blazor/skills/support-prerendering/SKILL.md +++ /dev/null @@ -1,216 +0,0 @@ ---- -license: MIT -name: support-prerendering -description: Make interactive Blazor components work correctly with prerendering. USE FOR fixing duplicate data loads, UI flicker during prerender-to-interactive handoff, null references during prerender, persisting state across prerender, disabling prerendering, excluding pages from interactive routing, or detecting whether a component is currently prerendering. DO NOT USE for choosing which render mode to use (see create-blazor-project) or general component authoring (see author-component). ---- - -# Support Prerendering - -## How Prerendering Works - -Prerendering is **on by default** for all interactive render modes. The server renders the component as static HTML and ships it to the browser immediately. Then the interactive runtime (Server/WebAssembly) loads and re-renders the component with full interactivity. - -This means: -- `OnInitializedAsync` runs **twice** — once during prerender (static), once when the interactive runtime attaches. -- `OnAfterRenderAsync` is **NOT** called during prerender — only after the interactive render. -- Internal navigation between interactive pages (interactive routing) **skips prerendering** — prerendering only happens on full page loads. - -## Step 1 — Read the Project's AGENTS.md - -Check the project's `AGENTS.md` for the **Interactivity Mode** and **Interactivity Scope**: - -| Mode | Prerendering applies? | -|------|----------------------| -| None (Static SSR) | No — there's no interactive handoff | -| Server | Yes | -| WebAssembly | Yes | -| Auto | Yes | - -If the mode is `None`, this skill doesn't apply. - -## Persist State Across Prerender → Interactive - -The most common prerendering problem: data loaded in `OnInitializedAsync` during prerender is thrown away and re-fetched when the interactive runtime attaches. This causes flicker and duplicate API/DB calls. - -### Recommended: `[PersistentState]` attribute - -Annotate properties to automatically serialize during prerender and restore on interactive activation: - -```razor -@page "/forecasts" -@rendermode InteractiveServer - -

Weather

- -@if (Forecasts is null) -{ -

Loading...

-} -else -{ - @foreach (var f in Forecasts) - { -

@f.Date: @f.TemperatureC°C

- } -} - -@code { - [PersistentState] - public WeatherForecast[]? Forecasts { get; set; } - - protected override async Task OnInitializedAsync() - { - Forecasts ??= await ForecastService.GetForecastsAsync(); - } -} -``` - -The `??=` pattern is critical — it means "only fetch if the property wasn't already restored from prerender state." - -### Multiple instances of the same component - -When the same component type appears multiple times, use `@key` to disambiguate state: - -```razor -@foreach (var item in items) -{ - -} -``` - -### Advanced: `PersistentComponentState` service - -For complex scenarios (dynamic keys, custom serialization), use the imperative API: - -```csharp -@inject PersistentComponentState ApplicationState - -@code { - private List? orders; - - protected override async Task OnInitializedAsync() - { - ApplicationState.RegisterOnPersisting(PersistOrders); - - if (!ApplicationState.TryTakeFromJson>("orders", out var restored)) - { - orders = await OrderService.GetOrdersAsync(); - } - else - { - orders = restored; - } - } - - private Task PersistOrders() - { - ApplicationState.PersistAsJson("orders", orders); - return Task.CompletedTask; - } -} -``` - -## Disable Prerendering - -Disable prerendering when a component depends on browser APIs immediately or when the prerender+interactive double render causes problems you can't solve with `[PersistentState]`. - -### On a component definition - -```razor -@rendermode @(new InteractiveServerRenderMode(prerender: false)) -``` - -Replace `InteractiveServerRenderMode` with `InteractiveWebAssemblyRenderMode` or `InteractiveAutoRenderMode` as needed. - -### On a component instance - -```razor - -``` - -### On the entire app - -In `App.razor`: - -```razor - - -``` - -Note: A parent's prerendering setting overrides children. If `` disables prerendering, individual pages cannot re-enable it. - -## Exclude Pages from Interactive Routing - -In a globally interactive app, some pages may need `HttpContext` (cookies, request headers, response status codes). These pages must render via static SSR, not inside the interactive runtime. - -Use `[ExcludeFromInteractiveRouting]`: - -```razor -@page "/privacy" -@attribute [ExcludeFromInteractiveRouting] - -

Privacy Policy

-``` - -This forces a **full page reload** when navigating to this page, exiting interactive routing. The page renders as static SSR with full `HttpContext` access. - -In `App.razor`, conditionally apply the render mode: - -```razor - - - - - - - - - - - -@code { - [CascadingParameter] - public HttpContext HttpContext { get; set; } = default!; - - private IComponentRenderMode? RenderModeForPage => - HttpContext.AcceptsInteractiveRouting() ? InteractiveServer : null; -} -``` - -Replace `InteractiveServer` with the app's configured render mode. - -## Detect Prerender vs Interactive at Runtime - -Use `RendererInfo` to guard code that should only run interactively: - -```csharp -protected override async Task OnInitializedAsync() -{ - if (RendererInfo.IsInteractive) - { - // Only runs during the interactive render, not during prerender - await StartSignalRConnection(); - } -} -``` - -`RendererInfo` properties: -- `IsInteractive` — `false` during prerender, `true` after interactive runtime attaches -- `Name` — `"Static"` during prerender, `"Server"` or `"WebAssembly"` when interactive - -## Client Services Fail During Prerender - -Components in the `.Client` project prerender on the server. Services registered only in the client `Program.cs` (e.g., `IWebAssemblyHostEnvironment`) won't be available during prerender. - -Fix by one of: -1. **Register a matching service on the server** — both `Program.cs` files provide the service -2. **Make the service optional** — use constructor injection with a nullable default: `public MyComponent(IMyService? svc = null)` -3. **Create a service abstraction** — interface in `.Client`, implementations in both projects -4. **Disable prerendering** for that component - -## Don'ts - -- Don't call JS interop in `OnInitializedAsync` — JS isn't available during prerender. Use `OnAfterRenderAsync(firstRender)`. -- Don't assume `OnInitializedAsync` runs once — it runs twice with prerendering. Always use `[PersistentState]` or `??=` guards. -- Don't use `HttpContext` in interactive components — it's only available during the static prerender, not during the interactive lifetime. Use `[ExcludeFromInteractiveRouting]` for pages that need it. -- Don't disable prerendering as a first resort — it hurts perceived load time and SEO. Use `[PersistentState]` to preserve state instead. diff --git a/plugins/dotnet-diag/skills/android-tombstone-symbolication/SKILL.md b/plugins/dotnet-diag/skills/android-tombstone-symbolication/SKILL.md deleted file mode 100644 index 1e549cd178..0000000000 --- a/plugins/dotnet-diag/skills/android-tombstone-symbolication/SKILL.md +++ /dev/null @@ -1,148 +0,0 @@ ---- -name: android-tombstone-symbolication -description: Symbolicate the .NET runtime frames in an Android tombstone file. Extracts BuildIds and PC offsets from the native backtrace, downloads debug symbols from the Microsoft symbol server, and runs llvm-symbolizer to produce function names with source file and line numbers. USE FOR triaging a .NET MAUI or Mono Android app crash from a tombstone, resolving native backtrace frames in libmonosgen-2.0.so or libcoreclr.so to .NET runtime source code, or investigating SIGABRT, SIGSEGV, or other native signals originating from the .NET runtime on Android. DO NOT USE FOR pure Java/Kotlin crashes, managed .NET exceptions that are already captured in logcat, or iOS crash logs. INVOKES Symbolicate-Tombstone.ps1 script, llvm-symbolizer, Microsoft symbol server. -license: MIT ---- - -# Android Tombstone .NET Symbolication - -Resolves native backtrace frames from .NET Android app crashes (MAUI, Xamarin, Mono) to function names, source files, and line numbers using ELF BuildIds and Microsoft's symbol server. - -**Inputs:** Tombstone file or logcat crash output, `llvm-symbolizer` (from Android NDK or any LLVM 14+ toolchain), internet access for symbol downloads. - -**Do not use when:** The crash is a managed .NET exception (visible in logcat with a managed stack trace), the crashing library is not a .NET component (e.g., `libart.so`), or the tombstone is from iOS. - ---- - -## Workflow - -### Step 1: Parse the Tombstone Backtrace - -Each backtrace frame has this format: - -``` -#NN pc OFFSET /path/to/library.so (optional_symbol+0xNN) (BuildId: HEXSTRING) -``` - -Extract: **frame number**, **PC offset** (hex, already library-relative), **library name**, and **BuildId** (32–40 hex chars). - -Symbolicate all threads by default (background threads like GC/finalizer often have useful .NET frames). The crashing thread's backtrace is listed first; additional threads appear after `--- --- ---` markers. - -**Format notes:** -- The script auto-detects `#NN pc` frame lines with or without a `backtrace:` header, and strips logcat timestamp/tag prefixes automatically. -- Logcat-captured tombstones often omit BuildIds. Recover via `adb shell readelf -n`, CI build artifacts, or the .NET runtime NuGet package. -- GitHub issue pastes may mangle `#1 pc` into issue links — replace `org/repo#N pc` with `#N pc` before saving to a file. -- If the script fails to parse a format, fall back to manual extraction of `#NN pc OFFSET library.so (BuildId: HEX)` tuples. - -### Step 2: Identify .NET Runtime Libraries - -Filter frames to .NET runtime libraries: - -| Library | Runtime | -|---------|---------| -| `libmonosgen-2.0.so` | Mono (MAUI, Xamarin, interpreter) | -| `libcoreclr.so` | CoreCLR (JIT mode) | -| `libSystem.*.so` | .NET BCL native components (`Native`, `Globalization.Native`, `IO.Compression.Native`, `Security.Cryptography.Native.OpenSsl`, `Net.Security.Native`) | - -**NativeAOT:** No `libcoreclr.so` or `libmonosgen-2.0.so` — the runtime is statically linked into the app binary (e.g., `libMyApp.so`). The `libSystem.*.so` BCL libraries remain separate and can be symbolicated via the symbol server. For the app binary itself, you need the app's own debug symbols. - -Skip `libc.so`, `libart.so`, and other Android system libraries unless the user specifically asks. - -### Step 3: Download Debug Symbols - -For each unique .NET BuildId, download debug symbols: - -``` -https://msdl.microsoft.com/download/symbols/_.debug/elf-buildid-sym-/_.debug -``` - -```bash -curl -sL "https://msdl.microsoft.com/download/symbols/_.debug/elf-buildid-sym-1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be/_.debug" \ - -o libmonosgen-2.0.so.debug -``` - -Verify with `file libmonosgen-2.0.so.debug` — should show `ELF 64-bit ... with debug_info, not stripped`. If the download returns 404 or HTML, symbols are not published for that build. Do not add or subtract library base addresses — offsets in tombstones are already library-relative. - -### Step 4: Symbolicate Each Frame - -```bash -llvm-symbolizer --obj=libmonosgen-2.0.so.debug -f -C 0x222098 -``` - -Output: -``` -ves_icall_System_Environment_FailFast -/__w/1/s/src/runtime/src/mono/mono/metadata/icall.c:6244 -``` - -The `/__w/1/s/` prefix is the CI workspace root — the meaningful path starts at `src/runtime/`, mapping to [dotnet/dotnet](https://github.com/dotnet/dotnet) VMR. - -### Step 5: Present the Symbolicated Backtrace - -Combine original frame numbers with resolved function names and source locations: - -``` -#00 libc.so abort+164 -#01 libmonosgen-2.0.so ves_icall_System_Environment_FailFast (mono/metadata/icall.c:6244) -#02 libmonosgen-2.0.so do_icall (mono/mini/interp.c:2457) -#03 libmonosgen-2.0.so mono_interp_exec_method (mono/mini/interp.c) -``` - -For unresolved frames (`??`), keep the original line with BuildId and PC offset. - -### Automation Script - -[scripts/Symbolicate-Tombstone.ps1](scripts/Symbolicate-Tombstone.ps1) automates the full workflow: - -```powershell -pwsh scripts/Symbolicate-Tombstone.ps1 -TombstoneFile tombstone_01.txt -LlvmSymbolizer llvm-symbolizer -``` - -Flags: `-CrashingThreadOnly` (limit to crashing thread), `-OutputFile path` (write to file), `-ParseOnly` (report libraries/BuildIds/URLs without downloading), `-SkipVersionLookup` (skip runtime version identification). - ---- - -## Finding llvm-symbolizer - -Check the **Android NDK** first: `$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/*/bin/llvm-symbolizer` or `$ANDROID_HOME/ndk/*/toolchains/llvm/prebuilt/*/bin/llvm-symbolizer`. Also available via `brew install llvm`, `apt install llvm`, or `xcrun --find llvm-symbolizer` on macOS. - -If unavailable, complete steps 1–3 and present the download commands and `llvm-symbolizer` commands for the user to run. Do not spend time installing LLVM. - ---- - -## Understanding the Output - -CI source paths use these prefixes: - -| Path prefix | Maps to | -|---|---| -| `/__w/1/s/src/runtime/` | `src/runtime/` in [dotnet/dotnet](https://github.com/dotnet/dotnet) VMR | -| `/__w/1/s/src/mono/` | `src/mono/` in the VMR (older builds) | -| `/__w/1/s/` | VMR root | - -### Runtime Version Identification - -The script identifies the exact .NET runtime version by matching BuildIds against locally-installed runtime packs. It searches: SDK packs (`$DOTNET_ROOT/packs/`), NuGet cache (`~/.nuget/packages/`), and NuGet.org as an online fallback. When found, it extracts the version and source commit from the `.nuspec` `` element. Pass `-SkipVersionLookup` to disable. Requires `llvm-readelf` (auto-discovered from the NDK). - ---- - -## Validation - -1. `file ` shows `ELF ... with debug_info, not stripped` -2. At least one .NET frame resolves to a function name (not `??`) -3. Resolved paths contain recognizable .NET runtime structure (e.g., `mono/metadata/`, `mono/mini/`) - -## Stop Signals - -- **No .NET frames found**: Report parsed frames and stop. -- **All frames resolved**: Present symbolicated backtrace. Do not trace into source or attempt to build/debug the runtime. -- **Symbols not available (404)**: One attempt per BuildId, then stop. Report unsymbolicated frames with BuildIds and offsets. -- **llvm-symbolizer not available**: Use `-ParseOnly`, present manual commands. Do not install LLVM. - -## Common Pitfalls - -- **Missing BuildIds**: Logcat tombstones often omit BuildIds. Recover via: `adb shell readelf -n /path/to/lib.so`, CI build artifacts, or the runtime NuGet package (`~/.dotnet/packs/Microsoft.NETCore.App.Runtime.Mono.android-arm64//`). Prefer pulling raw tombstone files (`adb shell cat /data/tombstones/tombstone_XX`) which always include BuildIds. -- **Symbols not found (404)**: Pre-release/internal builds may not publish symbols. Check for local unstripped `.so`/`.so.dbg` in build artifacts or the NuGet runtime pack. -- **NativeAOT**: No runtime `.so` in the tombstone — runtime is in the app binary. `libSystem.*.so` BCL libraries still work with the symbol server; the app binary needs its own debug symbols. -- **Wrong llvm-symbolizer version**: Use LLVM 14+ for best DWARF compatibility. -- **Multiple BuildIds**: Each .NET library has its own BuildId — download symbols for each separately. diff --git a/plugins/dotnet-diag/skills/android-tombstone-symbolication/scripts/Symbolicate-Tombstone.ps1 b/plugins/dotnet-diag/skills/android-tombstone-symbolication/scripts/Symbolicate-Tombstone.ps1 deleted file mode 100644 index 92f901e928..0000000000 --- a/plugins/dotnet-diag/skills/android-tombstone-symbolication/scripts/Symbolicate-Tombstone.ps1 +++ /dev/null @@ -1,749 +0,0 @@ -<# -.SYNOPSIS - Symbolicates .NET runtime frames in an Android tombstone file. - -.DESCRIPTION - Parses an Android tombstone file, extracts backtrace frames from .NET runtime - libraries (libmonosgen-2.0.so, libcoreclr.so, etc.), downloads debug symbols - from the Microsoft symbol server using the ELF BuildId, and runs llvm-symbolizer - to resolve each frame to function name, source file, and line number. - -.PARAMETER TombstoneFile - Path to the Android tombstone text file. - -.PARAMETER LlvmSymbolizer - Path to llvm-symbolizer. Defaults to 'llvm-symbolizer' (assumes it is on PATH). - -.PARAMETER SymbolCacheDir - Directory to cache downloaded debug symbol files. Defaults to a temp directory. - -.PARAMETER OutputFile - Optional path to write the symbolicated backtrace. If omitted, writes to stdout. - -.PARAMETER SymbolServerUrl - Base URL for the symbol server. Defaults to Microsoft's public server. - -.EXAMPLE - pwsh Symbolicate-Tombstone.ps1 -TombstoneFile tombstone_01.txt - -.EXAMPLE - pwsh Symbolicate-Tombstone.ps1 -TombstoneFile tombstone_01.txt -LlvmSymbolizer /path/to/llvm-symbolizer -OutputFile symbolicated.txt -#> - -[CmdletBinding()] -param( - [Parameter(Mandatory = $true)] - [string]$TombstoneFile, - - [Parameter()] - [string]$LlvmSymbolizer = 'llvm-symbolizer', - - [Parameter()] - [string]$SymbolCacheDir, - - [Parameter()] - [string]$OutputFile, - - [Parameter()] - [string]$SymbolServerUrl = 'https://msdl.microsoft.com/download/symbols', - - [Parameter()] - [switch]$CrashingThreadOnly, - - [Parameter()] - [switch]$ParseOnly, - - [Parameter()] - [switch]$SkipVersionLookup -) - -Set-StrictMode -Version Latest -$ErrorActionPreference = 'Stop' - -# Required for NuGet package inspection in Find-RuntimeVersionOnline -Add-Type -AssemblyName System.IO.Compression -ErrorAction SilentlyContinue - -# .NET runtime libraries we know how to symbolicate -$dotnetLibraries = @( - 'libmonosgen-2.0.so' - 'libcoreclr.so' - 'libSystem.Native.so' - 'libSystem.Globalization.Native.so' - 'libSystem.Security.Cryptography.Native.OpenSsl.so' - 'libSystem.IO.Compression.Native.so' - 'libSystem.Net.Security.Native.so' -) - -function Test-DotNetLibrary([string]$libraryName) { - foreach ($lib in $dotnetLibraries) { - if ($libraryName -like "*$lib*") { return $true } - } - return $false -} - -# Strip logcat prefixes from a line. -# Supports common logcat formats: -# threadtime (default): "05-06 11:27:48.795 2931 2931 F DEBUG : text" -# time: "05-06 11:27:48.795 F/DEBUG( 2931): text" -# brief: "F/DEBUG( 2931): text" -# Returns the content after the prefix, or the original line if no prefix found. -function Remove-LogcatPrefix([string]$line) { - # threadtime: MM-DD HH:MM:SS.mmm PID TID PRIO TAG : content - if ($line -match '^\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\.\d+\s+\d+\s+\d+\s+[A-Z]\s+.*?:\s*(.*)$') { - return $Matches[1] - } - # time: MM-DD HH:MM:SS.mmm PRIO/TAG(PID): content - if ($line -match '^\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\.\d+\s+[A-Z]/[^\(]+\(\s*\d+\):\s*(.*)$') { - return $Matches[1] - } - # brief: PRIO/TAG(PID): content - if ($line -match '^[A-Z]/[^\(]+\(\s*\d+\):\s*(.*)$') { - return $Matches[1] - } - return $line -} - -# Parse tombstone backtrace frames, grouped by thread -# Returns an array of thread objects, each with Header and Frames properties -function Get-BacktraceFrames([string[]]$lines, [bool]$firstThreadOnly) { - $threads = @() - $currentFrames = @() - $currentHeader = 'Crashing thread' - $inBacktrace = $false - - foreach ($rawLine in $lines) { - # Strip logcat prefix if present (CI systems often capture tombstones via logcat) - $line = Remove-LogcatPrefix $rawLine - # Thread separator — save current thread and start a new one - if ($line -match '^---\s+---\s+---') { - if ($currentFrames.Count -gt 0) { - $threads += [PSCustomObject]@{ Header = $currentHeader; Frames = @($currentFrames) } - if ($firstThreadOnly) { return @($threads) } - $currentFrames = @() - } - $inBacktrace = $false - $currentHeader = $null - continue - } - - # Thread header line — flush any accumulated frames as a new thread - # Standard tombstone format: "pid: NNN, tid: NNN, name: ..." - # Debuggerd short-form: "name (native):tid=NNN systid=NNN" - if ($line -match '^\s*pid:\s*\d+,\s*tid:\s*(\d+),\s*name:\s*(.+)' -or - $line -match '^\s*(\S.*?)\s*\(native\)\s*:\s*tid=(\d+)') { - if ($currentFrames.Count -gt 0) { - $threads += [PSCustomObject]@{ Header = $currentHeader; Frames = @($currentFrames) } - if ($firstThreadOnly) { return @($threads) } - $currentFrames = @() - $inBacktrace = $false - } - # Extract thread id and name (capture groups are in different order for the two patterns) - if ($line -match '^\s*pid:\s*\d+,\s*tid:\s*(\d+),\s*name:\s*(.+)') { - $threadId = $Matches[1]; $threadName = $Matches[2].Trim() - } else { - $line -match '^\s*(\S.*?)\s*\(native\)\s*:\s*tid=(\d+)' | Out-Null - $threadId = $Matches[2]; $threadName = $Matches[1].Trim() - } - # Keep 'Crashing thread' label for the first thread (before any separator) - if ($threads.Count -gt 0 -or $currentHeader -ne 'Crashing thread') { - $currentHeader = "Thread $threadId ($threadName)" - } - continue - } - - if ($line -match '^\s*backtrace:') { - $inBacktrace = $true - continue - } - - if ($line -match '^\s*#(\d+)\s+pc\s+(0x)?([0-9a-fA-F]+)\s+(\S+)(.*)$') { - $inBacktrace = $true - $frameNum = $Matches[1] - $pcOffset = '0x' + $Matches[3] - $libraryPath = $Matches[4] - $remainder = $Matches[5] - - $buildId = $null - if ($remainder -match '\(BuildId:\s*([0-9a-fA-F]+)\)') { - $buildId = $Matches[1].ToLowerInvariant() - } - - $existingSymbol = $null - if ($remainder -match '^\s*\(([^)]+)\)') { - $sym = $Matches[1] - if ($sym -notmatch '^BuildId:') { - $existingSymbol = $sym - } - } - - $libraryName = Split-Path $libraryPath -Leaf - - $currentFrames += [PSCustomObject]@{ - FrameNumber = [int]$frameNum - PcOffset = $pcOffset - LibraryPath = $libraryPath - LibraryName = $libraryName - BuildId = $buildId - ExistingSymbol = $existingSymbol - IsDotNet = (Test-DotNetLibrary $libraryName) - OriginalLine = $line.Trim() - } - } - elseif ($inBacktrace -and $line -match '^\s*#\d+\s+pc\s+') { - # Looks like a frame but didn't fully parse — warn about truncation/malformation - Write-Warning "Skipping malformed frame line: $($line.Trim())" - } - elseif ($inBacktrace -and $line -notmatch '^\s*#\d+' -and $line.Trim() -ne '') { - # End of this backtrace section - $inBacktrace = $false - } - } - - # Save the last thread - if ($currentFrames.Count -gt 0) { - $threads += [PSCustomObject]@{ Header = $currentHeader; Frames = @($currentFrames) } - } - - return @($threads) -} - -# Download debug symbols from the Microsoft symbol server -function Get-DebugSymbols([string]$buildId, [string]$cacheDir, [string]$serverUrl) { - $debugFile = Join-Path $cacheDir "$buildId.debug" - - if (Test-Path $debugFile) { - Write-Verbose "Using cached symbols for BuildId $buildId" - return $debugFile - } - - $url = "$serverUrl/_.debug/elf-buildid-sym-$buildId/_.debug" - Write-Verbose "Downloading symbols from $url" - - $savedProgressPreference = $ProgressPreference - try { - $ProgressPreference = 'SilentlyContinue' - Invoke-WebRequest -Uri $url -OutFile $debugFile -UseBasicParsing -TimeoutSec 120 - - # Verify the download is an ELF file (starts with 0x7f ELF) - $stream = [System.IO.File]::OpenRead($debugFile) - try { - $header = [byte[]]::new(4) - $bytesRead = $stream.Read($header, 0, 4) - } - finally { - $stream.Close() - } - if ($bytesRead -ge 4 -and $header[0] -eq 0x7f -and $header[1] -eq 0x45 -and $header[2] -eq 0x4c -and $header[3] -eq 0x46) { - $size = (Get-Item $debugFile).Length - Write-Verbose "Downloaded $([math]::Round($size / 1MB, 1)) MB debug symbols for BuildId $buildId" - return $debugFile - } - else { - Write-Warning "Downloaded file for BuildId $buildId is not a valid ELF file (symbols may not be published)" - Remove-Item $debugFile -ErrorAction SilentlyContinue - return $null - } - } - catch { - Write-Warning "Failed to download symbols for BuildId $buildId`: $_" - Remove-Item $debugFile -ErrorAction SilentlyContinue - return $null - } - finally { - $ProgressPreference = $savedProgressPreference - } -} - -# Try to identify the .NET runtime version and commit hash by matching a BuildId against -# locally-installed runtime packs (SDK workloads) and the NuGet package cache. -function Find-RuntimeVersion([string]$buildId, [string]$libraryName, [string]$llvmReadelf) { - # Map library name to candidate runtime pack names - $packNames = @() - if ($libraryName -like '*monosgen*') { - $packNames += 'Microsoft.NETCore.App.Runtime.Mono.android-{0}' - } - elseif ($libraryName -like '*coreclr*') { - $packNames += 'Microsoft.NETCore.App.Runtime.android-{0}' - } - else { - # libSystem.*.so can be in either pack - $packNames += 'Microsoft.NETCore.App.Runtime.Mono.android-{0}' - $packNames += 'Microsoft.NETCore.App.Runtime.android-{0}' - } - - $rids = @('arm64', 'arm', 'x64', 'x86') - $expandedPackNames = foreach ($tmpl in $packNames) { foreach ($rid in $rids) { $tmpl -f $rid } } - - # Build list of directories to search - $searchRoots = @() - - # 1. SDK packs folder (workload installs — most likely for MAUI apps) - $dotnetRoot = if ($env:DOTNET_ROOT) { $env:DOTNET_ROOT } - elseif (Test-Path (Join-Path $HOME '.dotnet')) { Join-Path $HOME '.dotnet' } - else { $null } - if ($dotnetRoot) { - foreach ($pn in $expandedPackNames) { - $p = Join-Path $dotnetRoot "packs/$pn" - if (Test-Path $p) { $searchRoots += $p } - } - } - - # 2. NuGet packages cache - $nugetDir = if ($env:NUGET_PACKAGES) { $env:NUGET_PACKAGES } - else { Join-Path $HOME '.nuget/packages' } - foreach ($pn in $expandedPackNames) { - $p = Join-Path $nugetDir $pn.ToLowerInvariant() - if (Test-Path $p) { $searchRoots += $p } - } - - foreach ($root in $searchRoots) { - foreach ($versionDir in (Get-ChildItem $root -Directory -ErrorAction SilentlyContinue)) { - # Find the native library under this version directory - $soFile = Get-ChildItem $versionDir.FullName -Recurse -Filter $libraryName -ErrorAction SilentlyContinue | Select-Object -First 1 - if (-not $soFile) { continue } - - # Read BuildId from the local binary - $localBuildId = $null - if ($llvmReadelf) { - $readelfOut = (& $llvmReadelf --notes $soFile.FullName 2>$null) -join "`n" - if ($readelfOut -match 'Build ID:\s*([0-9a-fA-F]+)') { - $localBuildId = $Matches[1].ToLowerInvariant() - } - } - if (-not $localBuildId) { continue } - if ($localBuildId -ne $buildId) { continue } - - # Match found — extract commit hash from .nuspec - $version = $versionDir.Name - $commit = $null - $nuspec = Get-ChildItem $versionDir.FullName -Filter '*.nuspec' -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 - if ($nuspec) { - try { - $xml = [xml](Get-Content $nuspec.FullName -Raw) - $repoNode = $xml.package.metadata.repository - if ($repoNode -and $repoNode.commit) { - $commit = $repoNode.commit - } - } - catch { - Write-Verbose "Could not parse nuspec for version $version`: $_" - } - } - - return [PSCustomObject]@{ - Version = $version - Commit = $commit - PackPath = $versionDir.FullName - } - } - } - - return $null -} - -# Fallback: query NuGet.org to identify the .NET version when the runtime pack is not installed locally. -# Downloads candidate nupkg files and checks the BuildId of the contained native library. -function Find-RuntimeVersionOnline([string]$buildId, [string]$libraryName, [string]$llvmReadelf, [string]$cacheDir) { - # Determine which NuGet package IDs and RIDs to try - $packNames = @() - if ($libraryName -like '*monosgen*') { - $packNames += 'Microsoft.NETCore.App.Runtime.Mono.android-{0}' - } - elseif ($libraryName -like '*coreclr*') { - $packNames += 'Microsoft.NETCore.App.Runtime.android-{0}' - } - else { - $packNames += 'Microsoft.NETCore.App.Runtime.Mono.android-{0}' - $packNames += 'Microsoft.NETCore.App.Runtime.android-{0}' - } - - # Try arm64 first (most common), then others - $rids = @('arm64', 'arm', 'x64', 'x86') - $packageIds = foreach ($tmpl in $packNames) { foreach ($rid in $rids) { ($tmpl -f $rid).ToLowerInvariant() } } - - $nugetBase = 'https://api.nuget.org/v3-flatcontainer' - $savedProgressPreference = $ProgressPreference - - try { - $ProgressPreference = 'SilentlyContinue' - - foreach ($pkgId in $packageIds) { - # List available versions - $indexUrl = "$nugetBase/$pkgId/index.json" - try { - $indexJson = Invoke-RestMethod -Uri $indexUrl -TimeoutSec 15 -UseBasicParsing - } - catch { - Write-Verbose "Could not fetch version index for $pkgId`: $_" - continue - } - - # Only check stable release versions (no previews/RCs), newest first - $versions = @($indexJson.versions | Where-Object { $_ -notmatch '-' }) | Sort-Object { [version]($_ -replace '[^0-9.]', '') } -Descending - - if ($versions.Count -eq 0) { continue } - Write-Host " Checking $($versions.Count) release versions of $pkgId on NuGet.org..." -ForegroundColor DarkGray - - foreach ($ver in $versions) { - $nupkgUrl = "$nugetBase/$pkgId/$ver/$pkgId.$ver.nupkg" - $nupkgFile = Join-Path $cacheDir "$pkgId.$ver.nupkg" - $extractDir = Join-Path $cacheDir "$pkgId.$ver" - - try { - # Download the nupkg (zip file) - if (-not (Test-Path $nupkgFile)) { - Invoke-WebRequest -Uri $nupkgUrl -OutFile $nupkgFile -UseBasicParsing -TimeoutSec 120 - } - - # Extract only the native library - if (-not (Test-Path $extractDir)) { - New-Item -ItemType Directory -Path $extractDir -Force | Out-Null - } - $zip = [System.IO.Compression.ZipFile]::OpenRead($nupkgFile) - try { - $entry = $zip.Entries | Where-Object { $_.Name -eq $libraryName } | Select-Object -First 1 - if (-not $entry) { - Remove-Item $nupkgFile -ErrorAction SilentlyContinue - continue - } - $soPath = Join-Path $extractDir $libraryName - if (-not (Test-Path $soPath)) { - [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $soPath, $true) - } - } - finally { - $zip.Dispose() - } - - # Check BuildId - $readelfOut = (& $llvmReadelf --notes $soPath 2>$null) -join "`n" - if ($readelfOut -match 'Build ID:\s*([0-9a-fA-F]+)') { - $localBuildId = $Matches[1].ToLowerInvariant() - if ($localBuildId -eq $buildId) { - # Match — extract commit from .nuspec inside the nupkg - $commit = $null - $zip2 = [System.IO.Compression.ZipFile]::OpenRead($nupkgFile) - try { - $nuspecEntry = $zip2.Entries | Where-Object { $_.FullName -like '*.nuspec' } | Select-Object -First 1 - if ($nuspecEntry) { - $reader = [System.IO.StreamReader]::new($nuspecEntry.Open()) - try { - $xml = [xml]$reader.ReadToEnd() - $repoNode = $xml.package.metadata.repository - if ($repoNode -and $repoNode.commit) { - $commit = $repoNode.commit - } - } - finally { $reader.Dispose() } - } - } - finally { $zip2.Dispose() } - - # Clean up downloaded packages (keep only the match) - Remove-Item $extractDir -Recurse -Force -ErrorAction SilentlyContinue - Remove-Item $nupkgFile -ErrorAction SilentlyContinue - - return [PSCustomObject]@{ - Version = $ver - Commit = $commit - PackPath = $null - } - } - } - - # No match — clean up this version - Remove-Item $extractDir -Recurse -Force -ErrorAction SilentlyContinue - Remove-Item $nupkgFile -ErrorAction SilentlyContinue - } - catch { - Write-Verbose "Failed to check version $ver`: $_" - Remove-Item $nupkgFile -ErrorAction SilentlyContinue - Remove-Item $extractDir -Recurse -Force -ErrorAction SilentlyContinue - } - } - } - } - finally { - $ProgressPreference = $savedProgressPreference - } - - return $null -} -function Resolve-Frame([string]$debugFile, [string]$pcOffset, [string]$symbolizerPath) { - try { - $output = & $symbolizerPath "--obj=$debugFile" -f -C $pcOffset 2>$null - if ($LASTEXITCODE -ne 0 -or -not $output) { return $null } - - $lines = $output -split "`n" | Where-Object { $_.Trim() -ne '' } - if ($lines.Count -ge 2) { - $functionName = $lines[0].Trim() - $sourceLocation = $lines[1].Trim() - - if ($functionName -eq '??' -and $sourceLocation -eq '??:0') { return $null } - - # Strip common CI build agent path prefixes (Azure DevOps hosted agents) - $sourceLocation = $sourceLocation -replace '^/__w/\d+/s/', '' - - return [PSCustomObject]@{ - Function = $functionName - Source = $sourceLocation - } - } - } - catch { - Write-Verbose "llvm-symbolizer failed for offset $pcOffset`: $_" - } - - return $null -} - -# --- Main --- - -if (-not (Test-Path $TombstoneFile)) { - Write-Error "Tombstone file not found: $TombstoneFile" - exit 1 -} - -# Set up symbol cache directory -if (-not $SymbolCacheDir) { - $SymbolCacheDir = Join-Path ([System.IO.Path]::GetTempPath()) 'dotnet-tombstone-symbols' -} -if (-not (Test-Path $SymbolCacheDir)) { - New-Item -ItemType Directory -Path $SymbolCacheDir -Force | Out-Null -} -Write-Verbose "Symbol cache: $SymbolCacheDir" - -# Read and parse tombstone -$tombstoneLines = Get-Content $TombstoneFile -$threads = Get-BacktraceFrames $tombstoneLines $CrashingThreadOnly - -$allFrames = @($threads | ForEach-Object { $_.Frames } | ForEach-Object { $_ }) -if ($allFrames.Count -eq 0) { - Write-Error "No backtrace frames found in $TombstoneFile" - exit 1 -} - -$dotnetFrames = @($allFrames | Where-Object { $_.IsDotNet }) -Write-Host "Found $($allFrames.Count) backtrace frames across $($threads.Count) thread(s) ($($dotnetFrames.Count) from .NET libraries)" -ForegroundColor Cyan - -if ($dotnetFrames.Count -eq 0) { - Write-Warning "No .NET runtime frames found in the backtrace. Nothing to symbolicate." - Write-Host "`nBacktrace frames found:" -ForegroundColor Yellow - foreach ($t in $threads) { - if ($t.Header) { Write-Host " $($t.Header)" } - foreach ($f in $t.Frames) { Write-Host " $($f.OriginalLine)" } - } - exit 0 -} - -# --- ParseOnly mode: report what was found without downloading or symbolicating --- -if ($ParseOnly) { - Write-Host "`n=== Tombstone Parse Report ===" -ForegroundColor Green - Write-Host "Threads: $($threads.Count)" - Write-Host "Total frames: $($allFrames.Count)" - Write-Host ".NET frames: $($dotnetFrames.Count)" - - $uniqueBuildIds = @($dotnetFrames | Where-Object { $_.BuildId } | Select-Object -ExpandProperty BuildId -Unique) - $framesWithoutBuildId = @($dotnetFrames | Where-Object { -not $_.BuildId }) - - Write-Host "`n--- .NET Libraries ---" - $libGroups = $dotnetFrames | Group-Object LibraryName - foreach ($g in $libGroups) { - $bidFrame = $g.Group | Where-Object { $_.BuildId } | Select-Object -First 1 - if ($bidFrame) { - Write-Host " $($g.Name) BuildId: $($bidFrame.BuildId) ($($g.Count) frame(s))" - Write-Host " Symbol URL: $SymbolServerUrl/_.debug/elf-buildid-sym-$($bidFrame.BuildId)/_.debug" - } - else { - Write-Host " $($g.Name) (no BuildId) ($($g.Count) frame(s))" - } - } - - if ($framesWithoutBuildId.Count -gt 0) { - Write-Host "`n--- Frames Without BuildId ---" - foreach ($f in $framesWithoutBuildId) { - Write-Host " #$($f.FrameNumber) $($f.LibraryName) pc $($f.PcOffset)" - } - } - - Write-Host "`n--- Frames to Symbolicate ---" - foreach ($t in $threads) { - if ($threads.Count -gt 1 -and $t.Header) { - Write-Host " [$($t.Header)]" - } - foreach ($f in $t.Frames) { - if ($f.IsDotNet) { - $marker = if ($f.BuildId) { "✓" } else { "✗ (no BuildId)" } - Write-Host " #$($f.FrameNumber) $($f.LibraryName) pc $($f.PcOffset) $marker" - } - } - } - - Write-Host "`n=== End Parse Report ===" - exit 0 -} - -# Collect unique BuildIds and download symbols -$buildIdMap = @{} # BuildId -> debug file path -$uniqueBuildIds = @($dotnetFrames | Where-Object { $_.BuildId } | Select-Object -ExpandProperty BuildId -Unique) -$framesWithoutBuildId = @($dotnetFrames | Where-Object { -not $_.BuildId }) - -if ($framesWithoutBuildId.Count -gt 0) { - Write-Warning "$($framesWithoutBuildId.Count) .NET frame(s) have no BuildId metadata — these cannot be symbolicated via the symbol server." -} - -if ($uniqueBuildIds.Count -eq 0) { - Write-Warning "No BuildIds found on any .NET frame. Outputting unsymbolicated backtrace." -} -else { - # Verify llvm-symbolizer is available (only needed when we have symbols to resolve) - $symbolizerCmd = Get-Command $LlvmSymbolizer -ErrorAction SilentlyContinue - - # If not on PATH, try common NDK locations - if (-not $symbolizerCmd) { - $ndkPaths = @() - if ($env:ANDROID_NDK_ROOT) { - $ndkPaths += Join-Path $env:ANDROID_NDK_ROOT 'toolchains/llvm/prebuilt/*/bin/llvm-symbolizer' - } - if ($env:ANDROID_HOME) { - $ndkPaths += Join-Path $env:ANDROID_HOME 'ndk/*/toolchains/llvm/prebuilt/*/bin/llvm-symbolizer' - } - foreach ($pattern in $ndkPaths) { - $found = Get-Item $pattern -ErrorAction SilentlyContinue | Select-Object -First 1 - if ($found) { - $LlvmSymbolizer = $found.FullName - $symbolizerCmd = Get-Command $LlvmSymbolizer -ErrorAction SilentlyContinue - break - } - } - } - - if (-not $symbolizerCmd) { - Write-Error "llvm-symbolizer not found. Set ANDROID_NDK_ROOT, add it to PATH, or pass -LlvmSymbolizer." - exit 1 - } - Write-Verbose "Using llvm-symbolizer: $($symbolizerCmd.Source)" - - Write-Host "Downloading debug symbols for $($uniqueBuildIds.Count) unique .NET BuildId(s)..." -ForegroundColor Cyan - foreach ($bid in $uniqueBuildIds) { - $lib = ($dotnetFrames | Where-Object { $_.BuildId -eq $bid } | Select-Object -First 1).LibraryName - Write-Host " $lib (BuildId: $bid)" -ForegroundColor DarkGray - $debugFile = Get-DebugSymbols $bid $SymbolCacheDir $SymbolServerUrl - if ($debugFile) { - $buildIdMap[$bid] = $debugFile - } - } - - $downloadedCount = $buildIdMap.Count - if ($downloadedCount -eq 0) { - Write-Warning "Could not download debug symbols for any .NET library. Outputting unsymbolicated backtrace." - } - else { - Write-Host "Successfully downloaded symbols for $downloadedCount/$($uniqueBuildIds.Count) BuildId(s)" -ForegroundColor Green - } - - # Try to identify .NET runtime version from locally-installed packs - $llvmReadelf = Join-Path (Split-Path $symbolizerCmd.Source) 'llvm-readelf' - if (-not (Test-Path $llvmReadelf)) { - $llvmReadelf = (Get-Command 'llvm-readelf' -ErrorAction SilentlyContinue)?.Source - } - $versionMap = @{} # BuildId -> version info - if (-not $SkipVersionLookup -and $llvmReadelf) { - Write-Host "Identifying .NET runtime version..." -ForegroundColor Cyan - foreach ($bid in $uniqueBuildIds) { - $lib = ($dotnetFrames | Where-Object { $_.BuildId -eq $bid } | Select-Object -First 1).LibraryName - $versionInfo = Find-RuntimeVersion $bid $lib $llvmReadelf - if (-not $versionInfo) { - # Fallback: search NuGet.org - Write-Host " Not found locally — searching NuGet.org..." -ForegroundColor DarkGray - $versionInfo = Find-RuntimeVersionOnline $bid $lib $llvmReadelf $SymbolCacheDir - } - if ($versionInfo) { - $versionMap[$bid] = $versionInfo - $commitShort = if ($versionInfo.Commit) { " (commit $($versionInfo.Commit.Substring(0, [Math]::Min(12, $versionInfo.Commit.Length))))" } else { '' } - Write-Host " $lib → .NET $($versionInfo.Version)$commitShort" -ForegroundColor Green - } - } - } -} - -# Symbolicate each frame, grouped by thread -Write-Host "`nSymbolicating backtrace..." -ForegroundColor Cyan -$output = @() -$resolvedCount = 0 - -foreach ($thread in $threads) { - if ($threads.Count -gt 1 -and $thread.Header) { - $output += "" - $output += "--- $($thread.Header) ---" - } - - foreach ($frame in $thread.Frames) { - if ($frame.IsDotNet -and $frame.BuildId -and $buildIdMap.ContainsKey($frame.BuildId)) { - $resolved = Resolve-Frame $buildIdMap[$frame.BuildId] $frame.PcOffset $LlvmSymbolizer - if ($resolved) { - $resolvedCount++ - # Keep last 2-3 path segments for context (e.g., "mono/metadata/icall.c:6244") - $sourceParts = $resolved.Source -split '/' - if ($sourceParts.Count -gt 3) { - $sourceShort = ($sourceParts[-3..-1]) -join '/' - } - elseif ($sourceParts.Count -gt 1) { - $sourceShort = ($sourceParts[-2..-1]) -join '/' - } - else { - $sourceShort = $resolved.Source - } - $line = "#{0:D2} {1,-24} {2,-48} ({3})" -f $frame.FrameNumber, $frame.LibraryName, $resolved.Function, $sourceShort - $output += $line - continue - } - } - - # Fallback: preserve original detail for triage (BuildId, path, symbol) - if ($frame.ExistingSymbol) { - $line = "#{0:D2} {1,-24} {2}" -f $frame.FrameNumber, $frame.LibraryName, $frame.ExistingSymbol - } - elseif ($frame.BuildId) { - $line = "#{0:D2} {1,-24} pc {2} (BuildId: {3})" -f $frame.FrameNumber, $frame.LibraryName, $frame.PcOffset, $frame.BuildId - } - else { - $line = "#{0:D2} {1,-24} pc {2} {3}" -f $frame.FrameNumber, $frame.LibraryName, $frame.PcOffset, $frame.LibraryPath - } - $output += $line - } -} - -# Output results -$header = @( - "--- Symbolicated Backtrace ---" - "" -) -$footer = @( - "" - "--- $resolvedCount of $($dotnetFrames.Count) .NET frame(s) symbolicated ---" -) - -# Append runtime version info if identified -if ($versionMap.Count -gt 0) { - $footer += "" - $footer += "--- .NET Runtime Version ---" - foreach ($bid in $versionMap.Keys) { - $vi = $versionMap[$bid] - $lib = ($dotnetFrames | Where-Object { $_.BuildId -eq $bid } | Select-Object -First 1).LibraryName - $commitInfo = if ($vi.Commit) { " Commit: https://github.com/dotnet/runtime/commit/$($vi.Commit)" } else { '' } - $footer += "$lib → .NET $($vi.Version)" - if ($commitInfo) { $footer += $commitInfo } - } -} - -$result = ($header + $output + $footer) -join "`n" - -if ($OutputFile) { - $result | Out-File -FilePath $OutputFile -Encoding utf8 - Write-Host "`nWrote symbolicated backtrace to $OutputFile" -ForegroundColor Green -} -else { - Write-Host "" - Write-Host $result -} diff --git a/plugins/dotnet-diag/skills/microbenchmarking/SKILL.md b/plugins/dotnet-diag/skills/microbenchmarking/SKILL.md deleted file mode 100644 index 9c7817cb03..0000000000 --- a/plugins/dotnet-diag/skills/microbenchmarking/SKILL.md +++ /dev/null @@ -1,137 +0,0 @@ ---- -name: microbenchmarking -description: > - Activate this skill when BenchmarkDotNet (BDN) is involved in the task — creating, - running, configuring, or reviewing BDN benchmarks. Also activate when - microbenchmarking .NET code would be useful and BenchmarkDotNet is the likely - tool. Consider activating when answering a .NET performance question requires - measurement and BenchmarkDotNet may be needed. - Covers microbenchmark design, BDN configuration and project setup, how to run - BDN microbenchmarks efficiently and effectively, and using BDN for side-by-side - performance comparisons. - Do NOT use for profiling/tracing .NET code (dotnet-trace, PerfView), production - telemetry, or load/stress testing (Crank, k6). -license: MIT ---- - -# Benchmark Authoring Guidelines - -BenchmarkDotNet (BDN) is a .NET library for writing and running microbenchmarks. Throughout this skill, "BDN" refers to BenchmarkDotNet. - -> **Note:** Evaluations of LLMs writing BenchmarkDotNet benchmarks have revealed common failure patterns caused by outdated assumptions about BDN's behavior — particularly around runtime comparison, job configuration, and execution defaults that have changed in recent versions. The reference files in this skill contain verified, current information. **You MUST read the reference files relevant to the task before writing any code** — your training data likely contains outdated or incorrect BDN patterns. - -## Key concepts - -- **Job** — describes how to run a benchmark: runtime, iteration counts, launch count, run strategy, and environment settings. Multiple jobs can be configured to run the same benchmarks under different conditions. -- **Benchmark case** — one method × one parameter combination × one job. The atomic unit BDN measures. -- **Operation** — the logical unit of work being measured. All BDN output columns (Mean, Error, etc.) report time per operation. -- **Invocation** — a single call to the benchmark method. By default, 1 invocation = 1 operation. With `OperationsPerInvoke=N`, each invocation counts as N operations. -- **Iteration** — a timed batch of invocations. BDN measures the total time for all invocations in an iteration, then divides by the total operation count to get per-operation time. - -## Benchmarks are comparative instruments - -A single benchmark number has limited value — it can confirm the order of magnitude of a measurement, but the exact value changes across machines, operating systems, and runtime configurations. Benchmarks produce the most useful information when compared against something. Before writing benchmarks, identify the **comparison axis** for the current task: - -- **Approaches (A vs B)**: comparing alternative implementations side-by-side in the same run. -- **Runtimes**: comparing the same code across .NET versions (e.g., net8.0 vs net9.0). -- **Package versions**: comparing different versions of a NuGet dependency. -- **Builds (before/after)**: comparing a saved DLL of the old code against the current source. -- **Runtime configuration (GC mode, JIT settings)**: understanding how runtime settings affect performance — compared via multiple jobs in a single run. -- **Scale (N=100 vs N=1000)**: understanding how performance changes as input size grows. -- **Hardware/OS**: comparing across different machines or operating systems — requires separate runs on each environment. -- **Historical measurements**: comparing against measurements recorded at a previous point in time. - -BDN can compare the first six axes side-by-side in a single run, but each requires specific CLI flags or configuration that differ from what you might expect — read [references/comparison-strategies.md](references/comparison-strategies.md) for the correct approach for each strategy before configuring a comparison. - -## Use cases and benchmark lifecycle - -There are four distinct reasons a developer writes a benchmark, and each one changes how the benchmark should be designed and where it should live: - -1. **Coverage suite**: Write benchmarks to maximize coverage of real-world usage patterns so that regressions affecting most users are caught. These benchmarks are permanent — they belong in the project's benchmark suite, follow its conventions (directory structure, base classes, naming), and are checked in. - -2. **Issue investigation**: Someone has reported a specific performance problem. Write benchmarks to reproduce and diagnose that specific issue. These benchmarks are task-scoped — they persist across the investigation (reproduce → isolate → verify fix) but are not part of the permanent suite. - -3. **Change validation**: A developer has a PR or change and wants to understand its performance characteristics before merging. These benchmarks are task-scoped — they persist across the review cycle but are not checked in. - -4. **Development feedback**: A developer is actively working on a task and wants to use benchmarks to evaluate approaches and get information early. These benchmarks are task-scoped and throwaway — they persist across the development session but are deleted when the decision is made. - -For use case 1, add to the existing benchmark project following its conventions. For use cases 2–4, create a standalone project in a working directory that persists for the task but is clearly not part of the permanent codebase. - -For **coverage suite** benchmarks, design from the perspective of real callers — what code patterns use this API, what inputs they pass, and what performance characteristics matter to them. Each permanent benchmark should justify its maintenance cost through real-world relevance. For **temporary benchmarks**, keep the case count intentional — each additional test case costs wall-clock time (read [Cost awareness](#cost-awareness)). - -## Cost awareness - -Each benchmark case (one method × one parameter combination × one job) takes **15–25 seconds** with default settings. `[Params]` creates a Cartesian product: two `[Params]` with 3 and 4 values across 5 methods = 60 cases ≈ 20 minutes. Multiple jobs multiply this further. Before running, estimate the total case count and match the job preset to the situation: - -| Preset | Per-case time | When to use | -|--------|--------------|-------------| -| `--job Dry` | <1s | Validate correctness — confirms compilation and execution without measurement | -| `--job Short` | 5–8s | Quick measurements during development or investigation | -| *(default)* | 15–25s | Final measurements for a coverage suite | -| `--job Medium` | 33–52s | Higher confidence when results matter | -| `--job Long` | 3–12 min | High statistical confidence | - -If benchmark runs take longer than expected, results seem unstable, or you need to tune iteration counts or execution settings, read [references/bdn-internals-and-tuning.md](references/bdn-internals-and-tuning.md) for detailed information about BDN's execution pipeline and configuration options. - -## Entry points and configuration - -BDN programs use either **`BenchmarkSwitcher`** (provides interactive benchmark selection for humans, parses CLI arguments) or **`BenchmarkRunner`** (runs specified benchmarks directly). Both support CLI flags like `--filter` and `--runtimes`, but only when `args` is passed through — without it, CLI flags are silently ignored. When using `BenchmarkSwitcher`, always pass `--filter` to avoid hanging on an interactive prompt. - -BDN behavior is customized through **attributes**, **config objects**, and **CLI flags**. - -Read [references/project-setup-and-running.md](references/project-setup-and-running.md) for entry point setup, config object patterns, and CLI flags. If you need to collect data beyond wall-clock time — such as memory allocations, hardware counters, or profiling traces — read [references/diagnosers-and-exporters.md](references/diagnosers-and-exporters.md). - -## Running benchmarks - -BenchmarkDotNet console output is extremely verbose — hundreds of lines per case showing internal calibration, warmup, and measurement details. Redirect all output to a file to avoid consuming context on verbose iteration output: - -``` -dotnet run -c Release -- --filter "*MethodName" --noOverwrite > benchmark.log 2>&1 -``` - -Each benchmark method can take several minutes. Rather than running all benchmarks at once, use `--filter` to run a subset at a time (e.g. one or two methods per invocation), read the results, then run the next subset. This keeps each invocation short — avoiding session or terminal timeouts — and lets you verify results incrementally. Read [references/project-setup-and-running.md](references/project-setup-and-running.md) for filter syntax, CLI flags, and project setup. - -After each run, read the Markdown report (`*-report-github.md`) from the results directory for the summary table. Only read `benchmark.log` if you need to investigate errors or unexpected results. - -## Writing new benchmarks - -### Step 1: Plan the test cases - -Before writing any code, determine: -- Which use case this benchmark serves (coverage, investigation, change validation, or development feedback). -- Which comparison axis applies (what will the number be compared against?). -- What real-world scenarios to benchmark, based on how callers actually use the API. - -Each benchmark case should justify its cost. An uncovered scenario is usually more valuable than another parameter combination for one already covered, but when a specific parameter dimension genuinely affects performance characteristics, the depth is warranted. - -Decide on the list of test cases. For each test case, think through: - -- **How to express variation**: BenchmarkDotNet provides several mechanisms for parameterizing benchmarks — `[Params]` and `[ParamsSource]` for property-level parameters, `[Arguments]` and `[ArgumentsSource]` for method-level arguments, `[ParamsAllValues]` to enumerate all values of a `bool` or enum, and `[GenericTypeArguments]` for varying type parameters on generic benchmark classes. Choose the mechanism that best fits the dimension being varied. Read [references/writing-benchmarks.md](references/writing-benchmarks.md) for the full set of options and correctness patterns. -- **Where input data comes from** — consider which sources are appropriate (these can be combined): - - Hard-coded values — small, fixed values where the exact input matters (e.g., specific strings, known edge-case sizes). Store in fields or `[Params]` to avoid constant folding. - - Asset files — static data that is too large or impractical to embed in source code such as binary blobs. - - Programmatically generated via `[ParamsSource]`/`[ArgumentsSource]`/`[GlobalSetup]` — when data shape matters more than specific content, or when input must be parameterized by size. -- **Whether randomness is appropriate**: If using generated data, use seeded randomness for reproducibility. When generating random data, use a large enough sample that the generated distribution is representative (e.g., 4 random values may cluster in a narrow range, while 1000 will better exercise the full distribution). - -### Step 2: Implement the benchmarks - -For **coverage suite** benchmarks, add to the existing benchmark project and follow its conventions. For **temporary benchmarks** (investigation, change validation, development feedback), create a standalone project — read [references/project-setup-and-running.md](references/project-setup-and-running.md) for project setup and entry point configuration. - -**Adding the BenchmarkDotNet package**: Always use `dotnet add package BenchmarkDotNet` (no version) — this lets NuGet resolve the latest compatible version. Do NOT manually write a `` with a version number into the `.csproj`; BDN versions in training data are outdated and may lack support for current .NET runtimes. - -Write the benchmark code. Follow the patterns in [references/writing-benchmarks.md](references/writing-benchmarks.md) to avoid common measurement errors — in particular: -- **Return results** from benchmark methods to prevent dead code elimination -- **Move initialization to `[GlobalSetup]`** — setup inside the benchmark method is measured; use `[IterationSetup]` only when the benchmark mutates state that must be reset between iterations -- **Do not add manual loops** — BDN controls invocation count automatically -- **Mark a baseline** when comparing alternatives — use `[Benchmark(Baseline = true)]` for method-level comparisons or `.AsBaseline()` on a job for multi-job comparisons so results show relative ratios -- **Store inputs in fields or `[Params]`**, not as literals or `const` values — the JIT can fold constant expressions at compile time, making the benchmark measure a precomputed result instead of the actual computation - -### Step 3: Validate and run - -Validate before committing to a long run: - -1. Run with `--job Dry` first to catch compilation errors and runtime exceptions without spending time on measurement. -2. Run a single representative case with default settings to verify the output looks correct and the numbers are in the expected range. -3. Only run the full suite after validation passes. - -When iterating on benchmark design, use `--job Short` until confident, then switch to default for final numbers. diff --git a/plugins/dotnet-diag/skills/microbenchmarking/references/bdn-internals-and-tuning.md b/plugins/dotnet-diag/skills/microbenchmarking/references/bdn-internals-and-tuning.md deleted file mode 100644 index 41728b867a..0000000000 --- a/plugins/dotnet-diag/skills/microbenchmarking/references/bdn-internals-and-tuning.md +++ /dev/null @@ -1,132 +0,0 @@ -# BenchmarkDotNet Execution and Configuration - -## Build and execution - -BDN generates a standalone project containing the measurement harness, builds it **once per unique build configuration**, and runs each case in its **own process**. Cases are partitioned into separate builds when they differ in factors including runtime, toolchain, platform, JIT, GC settings, build configuration, or MSBuild arguments. All cases sharing the same build configuration share a single build (~5s). - -BDN determines the number of invocations per iteration automatically. - -`[Params]` creates a full Cartesian product: two `[Params]` properties with 3 and 4 values across 5 methods = 3 × 4 × 5 = 60 cases. - -Build overhead (~5s) is paid once regardless of case count. When running cases individually (separate `dotnet run` per case), each pays the build cost, adding ~5s per case. - -## Execution stages per case (default job settings) - -Each case runs through these stages sequentially. Some stage defaults have changed between BDN versions and may change in future releases — check which version of the BenchmarkDotNet NuGet package is installed when the exact behavior matters. - -1. **Process launch + JIT** — The benchmark method is invoked to trigger initial JIT compilation, ensuring the method is compiled before the pilot stage calibrates invocation count. This stage's time is not included in results. -2. **Pilot** — Determines the invocation count per iteration. Fast methods get many invocations per iteration (targeting ~500ms per iteration). Methods slower than ~333ms/op (where two invocations would exceed the target) are fixed at one invocation per iteration. -3. **Warmup** — Adaptive, typically 6–10 iterations for stable benchmarks (those with low variance). During warmup the runtime may further optimize the method (e.g., tiered JIT recompilation). -4. **Actual** — Adaptive, typically 15 iterations for stable benchmarks. Stops when the confidence interval is sufficiently narrow (controlled by `MaxRelativeError`, default 2%). - -**Note (versions before 0.16.0):** prior to BDN 0.16.0, an additional **Overhead** stage ran between Pilot and Warmup by default. It measured the internal invocation loop's own cost and subtracted it from results. Starting in 0.16.0 this stage is off by default and the API to re-enable it (`[EvaluateOverhead]` / `.WithEvaluateOverhead()`) is marked obsolete. - -## Job preset configurations - -| Preset | Per-case time | Warmup | Target iterations | Launch count | Strategy | -|--------|--------------|--------|-------------------|-------------|----------| -| `Dry` | <1s | 0 | 1 | 1 | ColdStart | -| `Short` | 5–8s | 3 | 3 | 1 | Throughput | -| Default | 15–25s | 6–50 (adaptive) | 15–100 (adaptive) | 1 | Throughput | -| `Medium` | 33–52s | 10 | 15 | 2 | Throughput | -| `Long` | 3–12 min | 15 | 100 | 3 | Throughput | - -The `Dry` preset reuses the ColdStart strategy for minimal execution; its purpose is validation (confirming the benchmark compiles and runs), not first-call measurement. - -## Run strategies - -The `RunStrategy` controls how BDN calibrates and measures: - -- **Throughput** (default) — measures steady-state performance. BDN auto-calibrates invocation count via the pilot stage, runs warmup, and adapts iteration count. Use for microbenchmarks. -- **ColdStart** — single invocation per iteration, skips all preliminary stages (JIT pre-trigger, pilot, warmup, overhead). The first measured invocation includes JIT compilation time. Use for startup time evaluation. -- **Monitoring** — single invocation per iteration. Skips JIT pre-trigger, pilot, and overhead stages (like ColdStart), but includes the warmup stage (default 0 iterations, configurable). Use for macrobenchmarks with high variance that don't reach a steady state. - -## Jobs and mutators - -A **job** defines a complete set of run conditions — runtime, iteration counts, launch count, strategy, etc. A benchmark class can have **multiple jobs**, and BDN will run all benchmark methods under each job separately. For example, `[SimpleJob(RuntimeMoniker.Net80)]` and `[SimpleJob(RuntimeMoniker.Net90)]` on the same class runs every method twice — once per runtime. - -A **mutator** is not a standalone job. It is a partial override that gets applied to every existing job. This distinction matters when a class has multiple jobs: - -```csharp -[SimpleJob(RuntimeMoniker.Net80)] // Job A -[SimpleJob(RuntimeMoniker.Net90)] // Job B -[WarmupCount(3)] // Mutator — applied to BOTH Job A and Job B -public class MyBenchmarks { ... } -``` - -Without the mutator distinction, `[WarmupCount(3)]` would be a third job with just a warmup count override and default everything else — probably not what was intended. - -Jobs are resolved by collecting all standard jobs (from `[SimpleJob]`, etc.; `Job.Default` if none), then applying all mutators to every job. CLI flags like `--warmupCount 3` act as mutators — they override that setting on all jobs defined in source code. `--job Short` adds a standard job. - -## Execution-related attributes - -**Class or method level (mutator attributes):** -These override specific job settings. When applied to a method, they affect only that method's cases. When applied to a class, they affect all methods in the class. - -| Attribute | Default | Config (on Job) | CLI flag | -|-----------|---------|----------------|----------| -| `[WarmupCount(N)]` | null (adaptive) | `.WithWarmupCount(N)` | `--warmupCount N` | -| `[IterationCount(N)]` | null (adaptive) | `.WithIterationCount(N)` | `--iterationCount N` | -| `[MinWarmupCount(N)]` | 6 | `.WithMinWarmupCount(N)` | `--minWarmupCount N` | -| `[MaxWarmupCount(N)]` | 50 | `.WithMaxWarmupCount(N)` | `--maxWarmupCount N` | -| `[MinIterationCount(N)]` | 15 | `.WithMinIterationCount(N)` | `--minIterationCount N` | -| `[MaxIterationCount(N)]` | 100 | `.WithMaxIterationCount(N)` | `--maxIterationCount N` | -| `[InvocationCount(N)]` | null (auto pilot) | `.WithInvocationCount(N)` | `--invocationCount N` | -| `[IterationTime(ms)]` | 500ms | `.WithIterationTime(TimeInterval.FromMilliseconds(ms))` | `--iterationTime ms` | -| `[ProcessCount(N)]` | 1 | `.WithLaunchCount(N)` | `--launchCount N` | -| `[MaxRelativeError(pct)]` | 0.02 (= 2%) | `.WithMaxRelativeError(pct)` | — | - -Note: `[ProcessCount]` and `--launchCount` control the same setting (how many separate processes BDN launches per case). The naming differs between API surfaces. - -The `[RunOncePerIteration]` attribute (also available as `.RunOncePerIteration()` or `--runOncePerIteration`) is shorthand for setting `InvocationCount=1` and `UnrollFactor=1`. - -**Note (versions before 0.16.0):** `[EvaluateOverhead(bool)]` / `.WithEvaluateOverhead(bool)` / `--noOverheadEvaluation` controlled overhead subtraction. These are obsolete since 0.16.0 when overhead evaluation was disabled by default. - -**Class or assembly level:** -- Job attributes: `[SimpleJob(...)]`, `[DryJob]`, `[ShortRunJob]`, `[MediumRunJob]`, `[LongRunJob]`, `[VeryLongRunJob]`. AllowMultiple — can stack to run the same benchmarks under different job configurations. - -## Unroll factor - -BDN generates a measurement method that contains the benchmark code repeated `UnrollFactor` times (default 16). This reduces measurement loop overhead relative to the actual work. - -UnrollFactor is distinct from `OperationsPerInvoke`: UnrollFactor is an engine optimization, while `OperationsPerInvoke` is a user declaration that each invocation performs multiple logical operations. - -When `[IterationSetup]` or `[IterationCleanup]` is used, BDN defaults to `UnrollFactor=1` and `InvocationCount=1` so that setup/cleanup runs before and after each single invocation of the benchmark method. Explicitly setting `InvocationCount` or `UnrollFactor` overrides this behavior. - -| Attribute | Config API | CLI flag | -|-----------|------------|----------| -| `[UnrollFactor(N)]` | `.WithUnrollFactor(N)` | `--unrollFactor N` | - -## Execution environment - -The settings below configure the runtime environment the benchmark process runs in. They are orthogonal to the execution pipeline above — they don't change how many iterations run or how the engine measures, they change *what* is being measured. - -| Purpose | Attribute | Config API | CLI flag | -|---------|-----------|------------|----------| -| Target runtimes | `[SimpleJob(RuntimeMoniker.Net80)]` | `Job.Default.WithRuntime(CoreRuntime.Core80)` | `--runtimes net8.0 net9.0` (first is baseline) | -| Environment variables | — | `job.WithEnvironmentVariable("key", "value")` | `--envVars KEY:VALUE` | - -Multiple runtimes multiply the total case count and each requires a separate build. - -### GC configuration - -| Setting | Attribute | Config API | -|---------|-----------|------------| -| Server GC | `[GcServer(true)]` | `.WithGcServer(true)` | -| Concurrent GC | `[GcConcurrent(bool)]` | `.WithGcConcurrent(bool)` | - -### MemoryRandomization - -| Surface | Usage | -|---------|-------| -| Attribute | `[MemoryRandomization]` | -| Config | `.WithMemoryRandomization(true)` | -| CLI | `--memoryRandomization` | - -The `[MemoryRandomization]` attribute causes BDN to allocate random-sized memory between iterations, shifting heap object alignment. This reveals whether benchmark results depend on memory layout (cache line alignment, GC heap position) rather than algorithmic performance. - -When enabled, BDN: -- Allocates random-sized Gen0 and LOH objects between iterations -- Uses `stackalloc` with random size to shift stack alignment -- Re-runs `[GlobalCleanup]` and `[GlobalSetup]` after every iteration -- Disables outlier removal (since multimodal results may be genuine) diff --git a/plugins/dotnet-diag/skills/microbenchmarking/references/comparison-strategies.md b/plugins/dotnet-diag/skills/microbenchmarking/references/comparison-strategies.md deleted file mode 100644 index f161bd3e6c..0000000000 --- a/plugins/dotnet-diag/skills/microbenchmarking/references/comparison-strategies.md +++ /dev/null @@ -1,188 +0,0 @@ -# Comparing benchmark results - -BenchmarkDotNet can compare multiple implementations or versions in a single run, producing a side-by-side table with ratio columns and statistical analysis. This is generally preferable to separate runs because it controls for environmental variance. - -## Strategy 1: Side-by-side methods (preferred) - -When both the old and new implementations can coexist in the same compilation, define separate benchmark methods: - -```csharp -public class SortBenchmark -{ - private int[] _data; - - [GlobalSetup] - public void Setup() => _data = Enumerable.Range(0, 1000).Reverse().ToArray(); - - [Benchmark(Baseline = true)] - public void BubbleSort() => Sorting.BubbleSort((int[])_data.Clone()); - - [Benchmark] - public void QuickSort() => Sorting.QuickSort((int[])_data.Clone()); -} -``` - -BDN displays a Ratio column showing each method's mean relative to the baseline. This is the simplest approach and should be preferred whenever both implementations are available at compile time. - -## Strategy 2: Comparing runtimes - -To compare the same benchmark across different .NET runtime versions, use `--runtimes` on the command line or configure jobs. The `.csproj` must use `net8.0;net9.0` (plural) listing all targets: - -``` -dotnet run -c Release --framework net9.0 -- --runtimes net8.0 net9.0 -``` - -```csharp -var config = DefaultConfig.Instance - .AddJob(Job.Default.WithRuntime(CoreRuntime.Core80).AsBaseline()) - .AddJob(Job.Default.WithRuntime(CoreRuntime.Core90)); -``` - -Each runtime becomes a separate job. BDN builds separate executables per runtime and shows them side-by-side with ratio columns. - -## Strategy 3: Comparing NuGet package versions - -To compare different versions of a NuGet dependency, use MSBuild properties to control the package version per job. Each job gets a separate build with the specified version. - -**.csproj** — use an MSBuild property for the version: -```xml - - 2.0.0 - - - - -``` - -**Config** — create a job per version: -```csharp -var config = DefaultConfig.Instance - .AddJob(Job.Default - .WithMsBuildArguments("/p:MyLibVersion=1.0.0") - .WithId("v1.0.0") - .AsBaseline()) - .AddJob(Job.Default - .WithMsBuildArguments("/p:MyLibVersion=2.0.0") - .WithId("v2.0.0")); -``` - -All versions must be source-compatible with the benchmark code (same namespace, same method signatures). BDN builds a separate exe per job because `WithArguments` changes the build partition. - -This works with packages from any NuGet source — public registries, private feeds, or local folders created with `dotnet pack`. - -## Strategy 4: Comparing a saved build against current source (DLL reference) - -When the code is not published as a NuGet package but you want to compare before/after a code change, you can save the build output of the baseline version and reference it directly. - -**Step 1** — build and save the baseline: -``` -dotnet build ../MyLib -c Release -o ./saved-baseline -``` - -**Step 2** — make your changes to MyLib. - -**Step 3** — set up the benchmark .csproj with conditional references: -```xml - - - - $(BaselineDll) - - -``` - -**Step 4** — configure two jobs: -```csharp -var config = DefaultConfig.Instance - .AddJob(Job.Default - .WithMsBuildArguments("/p:BaselineDll=../saved-baseline/MyLib.dll") - .WithId("baseline") - .AsBaseline()) - .AddJob(Job.Default - .WithId("current")); -``` - -The `baseline` job builds with a direct DLL reference to the saved output. The `current` job builds with the `ProjectReference` to the current source. BDN produces a side-by-side table with ratio columns. - -This approach works for any class library. The namespace and public API must be the same between the two versions. - -## Strategy 5: Comparing runtime configurations - -To compare how different runtime settings (GC mode, JIT options, PGO) affect performance, define multiple jobs with different environment settings. This works with any `Job` setting — GC mode, environment variables, platform, JIT settings: - -```csharp -// GC mode comparison -var config = DefaultConfig.Instance - .AddJob(Job.Default.WithGcServer(false).WithId("Workstation GC").AsBaseline()) - .AddJob(Job.Default.WithGcServer(true).WithId("Server GC")); - -// JIT setting comparison -var config = DefaultConfig.Instance - .AddJob(Job.Default.WithId("Default").AsBaseline()) - .AddJob(Job.Default.WithEnvironmentVariable("DOTNET_TieredCompilation", "0").WithId("No Tiered")); -``` - -## Strategy 6: Comparing across input scale - -Use `[Params]` on a size property to understand how performance changes with input size. BDN runs each parameter value as a separate case. Geometrically spaced values (e.g., 10×, 100×) help reveal scaling behavior: - -```csharp -[Params(100, 1_000, 10_000)] -public int N; - -private int[] _data; - -[GlobalSetup] -public void Setup() -{ - var rng = new Random(42); - _data = Enumerable.Range(0, N).OrderBy(_ => rng.Next()).ToArray(); -} - -[Benchmark] -public void Sort() => Array.Sort((int[])_data.Clone()); -``` - -## How it works - -All multi-version strategies rely on the same BDN mechanism: - -1. **Build partitioning** — different MSBuild arguments, runtimes, or platform → separate compiled executables. Each case runs in its own process. -2. **Ratio calculation** — when a baseline is marked, BDN adds `Ratio` and `RatioSD` columns. `Ratio` is the mean of current/baseline per-operation time ratios. A `Ratio` of `0.85` means ~15% faster. - -### Marking a baseline - -For side-by-side methods (Strategy 1), mark one method with `[Benchmark(Baseline = true)]`. This compares methods within each job. - -For multi-job strategies (Strategies 2–5), mark one job with `.AsBaseline()` in the config. This compares jobs against each other. For `--runtimes`, the first runtime listed is the baseline. - -These are separate mechanisms — using the wrong one produces no ratio columns. - -Without a baseline, BDN shows absolute numbers only — no ratio columns. - -## Apples-to-apples comparison - -When comparing across jobs (Strategies 2–5), the default behavior runs each job's pilot stage independently, which may choose different invocation counts per job for the same benchmark case. This creates asymmetric measurement conditions that can bias the comparison. - -The `--apples` flag forces symmetric measurement by running in two phases: - -1. **Pilot phase** — BDN runs the baseline job once per benchmark case (method × parameter combination) to determine the invocation count for that case. Different cases get different invocation counts based on their speed. This produces a first results table in the log showing only the baseline with `Ratio = 1.00`. -2. **Measurement phase** — for each benchmark case, ALL jobs run with that case's fixed invocation count, ensuring every job measures the same number of operations per iteration. The final comparison table includes `Ratio` and `InvocationCount` columns and is written to `BenchmarkDotNet.Artifacts/`. - -Outlier removal is disabled in this mode since the controlled setup makes outliers more meaningful. - -``` -dotnet run -c Release --framework net9.0 -- --runtimes net8.0 net9.0 --apples --job short -``` - -Because the pilot runs only once per benchmark case instead of once per job, `--apples` is faster than the default when there are many benchmark cases. The savings grow with the number of methods and parameter combinations. - -Requirements: -- At least two jobs, with exactly one marked as baseline (via `.AsBaseline()` on the job, not `[Benchmark(Baseline = true)]` on the method). When using `--runtimes`, the first runtime listed is automatically treated as the baseline. -- An explicit iteration count, such as by using `--job short` (which sets `IterationCount=3`) or `--iterationCount N`. Adaptive iteration count is disabled in this mode. - -This does not apply to Strategy 1 (side-by-side methods) or Strategy 6 (input scale) because those use a single job — `--apples` requires multiple job objects. - -## Mann-Whitney equivalence test - -BDN can add a `Faster` / `Same` / `Slower` column based on a Mann-Whitney equivalence test. Add it via config: `.AddColumn(StatisticalTestColumn.Create(threshold: "5%"))`. The `threshold` is the equivalence margin — results within that percentage are reported as `Same`. diff --git a/plugins/dotnet-diag/skills/microbenchmarking/references/diagnosers-and-exporters.md b/plugins/dotnet-diag/skills/microbenchmarking/references/diagnosers-and-exporters.md deleted file mode 100644 index 643f74651d..0000000000 --- a/plugins/dotnet-diag/skills/microbenchmarking/references/diagnosers-and-exporters.md +++ /dev/null @@ -1,143 +0,0 @@ -# Measurement and diagnostics - -BenchmarkDotNet measures wall-clock time by default. This reference covers how to collect additional data (allocations, disassembly, hardware counters), customize statistical output, and export results. - -## Diagnosers - -Diagnosers add columns or produce artifacts beyond basic timing. They are enabled via class-level attributes or CLI flags. - -### MemoryDiagnoser - -| Surface | Usage | -|---------|-------| -| Attribute | `[MemoryDiagnoser]` or `[MemoryDiagnoser(displayGenColumns: false)]` | -| Config | `.AddDiagnoser(MemoryDiagnoser.Default)` | -| CLI | `--memory` | - -Tracks managed heap allocations and GC collections per operation. - -Adds columns: `Gen0`, `Gen1`, `Gen2` (GC collections per 1000 operations — a value of `1.0000` means one collection per 1000 operations), `Allocated` (bytes per operation). - -Set `displayGenColumns: false` if only total allocated bytes matter. - -### DisassemblyDiagnoser - -| Surface | Usage | -|---------|-------| -| Attribute | `[DisassemblyDiagnoser(maxDepth: 2)]` | -| Config | `.AddDiagnoser(new DisassemblyDiagnoser(new DisassemblyDiagnoserConfig(maxDepth: 2, printSource: true)))` | -| CLI | `--disasm`, `--disasmDepth N`, `--disasmDiff`, `--disasmFilter "Method*"` | - -Captures the JIT-compiled assembly code for the benchmark method. - -Produces: a per-benchmark disassembly report (exported as GitHub Markdown and/or HTML). - -Config options (`DisassemblyDiagnoserConfig`): -- `maxDepth` (default 1) — how many levels of called methods to include in the disassembly. -- `syntax` — `DisassemblySyntax.Masm` (default), `Intel`, or `Att` -- `printSource` (default false) — include C#/F#/VB source alongside assembly -- `exportDiff` (default false) — when comparing multiple jobs, export a diff view -- `exportCombinedDisassemblyReport` (default false) — all benchmarks in a single HTML report for side-by-side comparison - -When using `printSource: true`, ensure the benchmark project emits PDB files so BDN can map assembly instructions to source lines: - -```xml -pdbonly -true -``` - -### ThreadingDiagnoser - -`[ThreadingDiagnoser]` (CLI: `--threading`, Config: `.AddDiagnoser(ThreadingDiagnoser.Default)`) — adds `Completed Work Items` and `Lock Contentions` columns. - -### EventPipeProfiler - -| Surface | Usage | -|---------|-------| -| Attribute | `[EventPipeProfiler(EventPipeProfile.CpuSampling)]` | -| Config | `.AddDiagnoser(new EventPipeProfiler(EventPipeProfile.CpuSampling))` | -| CLI | `--profiler EP` | - -Collects CPU sampling profiles using .NET's EventPipe infrastructure. Cross-platform. - -Profiles available: `CpuSampling`, `GcVerbose`, `GcCollect`, `Jit`. - -Produces: `.nettrace` and `.speedscope.json` files. By default (attribute/config), runs an extra benchmark iteration dedicated to profiling so timing results are unaffected. - -**CLI note:** `--profiler EP` uses `CpuSampling` with `performExtraBenchmarksRun: false` — profiling is attached to normal measurement runs (no extra iteration, results include profiler overhead, no way to select a different profile). Use the attribute or config API for full control. - -### HardwareCounters (Windows only, requires elevation) - -| Surface | Usage | -|---------|-------| -| Attribute | `[HardwareCounters(HardwareCounter.CacheMisses, HardwareCounter.BranchMispredictions)]` | -| Config | `.AddHardwareCounters(HardwareCounter.CacheMisses, HardwareCounter.BranchMispredictions)` | -| CLI | `--counters CacheMisses+BranchMispredictions` | - -Collects CPU hardware performance counters via ETW. - -Available counters include: `TotalCycles`, `InstructionRetired`, `CacheMisses`, `BranchMispredictions`, `BranchInstructions`, `LlcMisses`, `LlcReference`. - -Requires: Windows, elevated (admin) process, and ETW support. Not available on all hardware. - -## Statistical output - -### Default columns - -| Column | Meaning | -|--------|---------| -| `Mean` | Average per-operation time across all measured iterations | -| `Error` | Half-width of the 99.9% confidence interval — if large relative to Mean, results are noisy | -| `StdDev` | Standard deviation of measurements (hidden when negligible) | -| `Median` | Median per-operation time (auto-shown when data is skewed or median diverges from mean) | -| `P95` | 95th percentile (auto-shown when extreme outliers are present) | -| `Ratio` | Performance relative to the baseline (current / baseline) — only shown when a baseline is marked. A value of `0.85` means ~15% faster. See [comparison-strategies.md](comparison-strategies.md) for how this is calculated | -| `RatioSD` | Standard deviation of the ratio distribution | - -### Adding columns - -Additional statistics can be added via attributes on the benchmark class: - -| Attribute | Column added | -|-----------|-------------| -| `[MedianColumn]` | Median (P50) | -| `[MinColumn]`, `[MaxColumn]` | Minimum, Maximum | -| `[Q1Column]`, `[Q3Column]` | First quartile (P25), Third quartile (P75) | -| `[AllStatisticsColumn]` | Mean, StdErr, StdDev, Ops/s, Min, Q1, Median, Q3, Max | -| `[RankColumn]` | Rank (1, 2, 3...) | -| `[SkewnessColumn]`, `[KurtosisColumn]` | Distribution shape metrics | -| `[OperationsPerSecond]` | Throughput (ops/sec) | - -Percentile columns are available via code: `StatisticColumn.P50`, `StatisticColumn.P85`, `StatisticColumn.P95`, etc. - -### Hiding columns - -Use `[HideColumns]` to remove unwanted columns from the output: - -```csharp -[HideColumns("Error", "StdDev", "RatioSD")] -public class MyBenchmark { ... } -``` - -## Outlier handling - -| Surface | Usage | -|---------|-------| -| Attribute | `[Outliers(OutlierMode.DontRemove)]` | -| Config | `.WithOutlierMode(OutlierMode.DontRemove)` | -| CLI | `--outliers DontRemove` | - -By default, BDN removes upper outliers (unusually slow iterations, typically caused by GC or OS interference). Available modes: `DontRemove`, `RemoveUpper` (default), `RemoveLower`, `RemoveAll`. - -## Export formats - -BDN exports results in multiple formats. By default it produces Markdown and CSV in the `BenchmarkDotNet.Artifacts/results/` directory. - -| Format | Default | Config | CLI flag | -|--------|---------|--------|----------| -| JSON (full, indented) | no | `.AddExporter(JsonExporter.Full)` | `--exporters fulljson` | -| JSON (compressed) | no | `.AddExporter(JsonExporter.Default)` | `--exporters json` | -| CSV | yes | `.AddExporter(CsvExporter.Default)` | `--exporters csv` | -| GitHub Markdown | yes | `.AddExporter(MarkdownExporter.GitHub)` | `--exporters github` | - -Use `JsonExporter.Full` for individual measurements (needed for programmatic comparison). diff --git a/plugins/dotnet-diag/skills/microbenchmarking/references/project-setup-and-running.md b/plugins/dotnet-diag/skills/microbenchmarking/references/project-setup-and-running.md deleted file mode 100644 index c46ec7dd64..0000000000 --- a/plugins/dotnet-diag/skills/microbenchmarking/references/project-setup-and-running.md +++ /dev/null @@ -1,179 +0,0 @@ -# Running benchmarks - -This reference covers how to build, run, and read BenchmarkDotNet results. It also covers common CLI flags for controlling output and debugging. - -## Entry points: BenchmarkSwitcher vs BenchmarkRunner - -BenchmarkDotNet programs use one of two entry points. This determines whether CLI arguments work: - -**BenchmarkSwitcher** — passes `args` to BDN, CLI flags work: -```csharp -BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); -BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args, config); // with config -``` - -**BenchmarkRunner** — only forwards args if explicitly passed: -```csharp -BenchmarkRunner.Run(); // CLI flags IGNORED -BenchmarkRunner.Run(args: args); // CLI flags work -BenchmarkRunner.Run(config); // config only, no CLI -BenchmarkRunner.Run(config, args); // both config and CLI -``` - -Before passing CLI flags like `--filter` or `--job`, check which entry point the program uses. If it uses `BenchmarkRunner.Run()` without args, CLI flags will be silently ignored — configuration must be done through attributes and `ManualConfig` instead. - -**Critical**: when `BenchmarkSwitcher` is used, it prompts the user interactively to select which benchmarks to run unless `--filter` is provided. For AI agents, always pass `--filter` to avoid hanging on an interactive prompt. `--filter "*"` matches everything and is the standard way to run all benchmarks non-interactively. - -## Config objects - -Configs can be built in three ways: - -**Modify the default config** — starts with all default loggers, exporters, and columns: -```csharp -var config = DefaultConfig.Instance - .AddJob(Job.Default.WithRuntime(CoreRuntime.Core90)) - .AddDiagnoser(MemoryDiagnoser.Default); -``` - -**Subclass ManualConfig** — useful when config is complex or reused across classes: -```csharp -public class MyConfig : ManualConfig -{ - public MyConfig() - { - AddJob(Job.Default.WithRuntime(CoreRuntime.Core80)); - AddJob(Job.Default.WithRuntime(CoreRuntime.Core90).AsBaseline()); - AddDiagnoser(MemoryDiagnoser.Default); - } -} -``` - -**Start from empty** — `ManualConfig.CreateEmpty()` removes all defaults (no loggers, no exporters, no columns). Use `ManualConfig.CreateMinimumViable()` instead to start with the default columns and console logger. - -Configs can be applied in several ways: - -| Method | Scope | -|--------|-------| -| `BenchmarkRunner.Run(config)` | All benchmarks in the run | -| `BenchmarkSwitcher...Run(args, config)` | All benchmarks in the run | -| `[Config(typeof(MyConfig))]` on class or assembly | That class, or all classes in the assembly | - -## Creating a new benchmark project - -If there is no existing benchmark project to add to, create a new console project with `dotnet new console` and add the BenchmarkDotNet package. Choose a temporary or permanent location based on the scope of the work. - -Use `dotnet add package BenchmarkDotNet` without specifying a version — `dotnet` resolves the latest compatible version automatically. Pinning to a specific version risks missing support for newer runtimes and CLI features. - -**Multi-runtime targeting**: to compare across runtimes (e.g., `--runtimes net8.0 net9.0`), the `.csproj` must use the plural `` property listing all targets: - -```xml -net8.0;net9.0 -``` - -If the project uses the singular `` with only one TFM, multi-runtime runs will fail at build time. - -Then replace `Program.cs` with: -```csharp -using BenchmarkDotNet.Running; - -BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); -``` - -Adjust the `ProjectReference` path to match the project under test. If benchmarking code that isn't in a separate project, skip `dotnet add reference` and put the code under test directly in the benchmark project. - -## Build and run strategy - -BenchmarkDotNet console output is extremely verbose — hundreds of lines per case showing pilot, warmup, and actual iteration details. Redirect all output to a file to avoid consuming context on verbose iteration output. - -**Recommended approach**: build first, then run with output redirected to a file. Always pass `--noOverwrite` so each run writes results to a timestamped subdirectory instead of `BenchmarkDotNet.Artifacts/results/` — without it, each run overwrites the previous results, making it easy to get confused about which run the results are for. - -Each benchmark method can take several minutes. Rather than running all benchmarks at once, use `--filter` to run a subset at a time (e.g. one or two methods per invocation), read the results, then run the next subset. This keeps each invocation short — avoiding session or terminal timeouts — and lets you verify results incrementally. - -``` -dotnet build -c Release -dotnet run -c Release --no-build -- --filter "*MethodName" --noOverwrite > benchmark.log 2>&1 -``` - -After each run, read the Markdown report (`*-report-github.md`) for the summary table. Only read `benchmark.log` if you need to investigate errors or unexpected results. - -## Artifacts directory - -By default, BDN writes to `BenchmarkDotNet.Artifacts/` relative to the working directory. Override with: - -``` -dotnet run -c Release --no-build -- --artifacts ./my-results -``` - -The artifacts directory contains: -``` -BenchmarkDotNet.Artifacts/ -├── MyBenchmark-20240101-120000.log # full console log -└── results/ - ├── MyBenchmark-report-github.md # markdown summary table - └── MyBenchmark-report.csv # CSV data -``` - -Use `--noOverwrite` to prevent overwriting previous results (writes to `BenchmarkDotNet.Artifacts//` instead of `BenchmarkDotNet.Artifacts/results/`). Use `--artifacts` with different paths when comparing results from separate runs. - -## Useful CLI flags for agents - -### Filtering and discovery - -| Flag | Purpose | -|------|---------| -| `--filter "*"` | Run all benchmarks (avoids interactive prompt from BenchmarkSwitcher) | -| `--filter "*.MethodName"` | Run specific benchmark methods | -| `--list flat` | List available benchmark names without running them | -| `--list tree` | List benchmarks in a tree hierarchy | -| `--allCategories ` | Run only benchmarks matching all specified categories | -| `--anyCategories ` | Run benchmarks matching any specified category | - -Tag benchmarks with `[BenchmarkCategory("name")]` (on methods, classes, or assemblies) to enable category-based filtering. - -**How `--filter` works**: BDN matches each pattern against two forms of the benchmark name: -- **Short form**: `Namespace.ClassName.MethodName` (no parameters) -- **Full form**: `Namespace.ClassName.MethodName(param: value, ...)` (includes parameters when present) - -Patterns use glob wildcards (`*` = any characters, `?` = single character), are **case-insensitive**, and must match the **entire** name (anchored). Multiple `--filter` values are OR'd — a case runs if it matches any pattern. - -| Goal | Pattern | -|------|---------| -| Run all benchmarks | `--filter "*"` | -| Run one method by name | `--filter "*MyMethod"` | -| Run all methods in a class | `--filter "*MyClass*"` | -| Run a specific class.method | `--filter "MyNamespace.MyClass.MyMethod"` | -| Same, using wildcard for namespace | `--filter "*MyClass.MyMethod"` | -| Run two specific methods | `--filter "*MethodA" --filter "*MethodB"` | -| Run methods matching a substring | `--filter "*Sort*"` | - -**Tip**: because patterns are anchored, `--filter "MyMethod"` does **not** match `MyNamespace.MyClass.MyMethod` — always use a leading `*` unless matching the short form exactly. Use `--list flat` to see the exact names BDN uses for filtering. - -**Category-based filtering**: tag benchmarks with `[BenchmarkCategory("name")]` on methods, classes, or assemblies to enable category filtering. Categories are inherited — a method tagged `"Parsing"` on a class tagged `"Strings"` has both categories. - -| Flag | Behavior | -|------|----------| -| `--anyCategories Parsing Sorting` | Run benchmarks that have **at least one** of the listed categories | -| `--allCategories Strings Parsing` | Run benchmarks that have **all** of the listed categories | - -When `--filter` and `--allCategories`/`--anyCategories` are used together, a benchmark must satisfy **both** — the glob filter AND the category filter are AND'd together. - -### Output control - -| Flag | Purpose | -|------|---------| -| `--artifacts ./path` | Change where results are written | -| `--noOverwrite` | Don't overwrite previous result files | -| `--exporters json` | Add JSON export (useful for programmatic comparison) | -| `--join` | Combine results from multiple benchmark classes into a single table | -| `--hide "Error" "StdDev"` | Hide specific columns from the results table | -| `--keepFiles` | Keep the generated benchmark project files — useful for debugging build failures | - -## Dry run validation - -Always run `--job Dry` first to catch compilation and runtime errors before committing to a full run: - -``` -dotnet run -c Release --no-build -- --filter "*" --job Dry --noOverwrite -``` - -A dry run executes each case once (<1 second per case) without meaningful measurement. It validates that setup methods work, parameters are valid, and the benchmark compiles and executes. Only after dry validation passes should you run with default or other job presets. diff --git a/plugins/dotnet-diag/skills/microbenchmarking/references/writing-benchmarks.md b/plugins/dotnet-diag/skills/microbenchmarking/references/writing-benchmarks.md deleted file mode 100644 index 586638e9db..0000000000 --- a/plugins/dotnet-diag/skills/microbenchmarking/references/writing-benchmarks.md +++ /dev/null @@ -1,296 +0,0 @@ -# Benchmark authoring techniques - -This reference covers BenchmarkDotNet features and practices for writing correct benchmark methods. Incorrect benchmarks silently produce misleading results — the techniques here prevent common measurement errors. - -## Dead code elimination - -The JIT compiler can eliminate code whose result is never used. If a benchmark method returns `void` and doesn't store its result anywhere observable, the JIT may partially or fully optimize away the computation. - -**Returning a value from the benchmark method prevents this.** When the method has a non-void return type, the JIT cannot prove the result is unused (the call site in BDN's generated harness is opaque to the JIT), so it must preserve the computation: - -```csharp -// Correct — non-void return prevents DCE -[Benchmark] -public int Parse() => int.Parse("12345"); - -// Wrong — void return, JIT may eliminate the call -[Benchmark] -public void Parse() => int.Parse("12345"); -``` - -For benchmarks that must return `void` (e.g., methods with side effects like `Array.Sort`), DCE is not a concern because the operation itself has observable effects. - -For iterating deferred sequences where returning the sequence object doesn't force enumeration, use the `Consumer` class explicitly — see [Deferred execution](#deferred-execution). - -## Setup and cleanup - -### GlobalSetup / GlobalCleanup - -A method marked `[GlobalSetup]` runs once per benchmark case, before all iterations of that case. Use it to allocate buffers, load data, and initialize state that the benchmark reads but does not mutate. - -```csharp -private int[] _array; - -[GlobalSetup] -public void Setup() => _array = Enumerable.Range(0, 1000).ToArray(); - -[Benchmark] -public int Sum() => _array.Sum(); -``` - -Initialization logic inside the benchmark method itself is measured — this is almost never what you want. - -When a class has multiple benchmarks needing different setup, use the `Target` or `Targets` property: - -```csharp -[GlobalSetup(Target = nameof(BenchmarkA))] -public void SetupA() { ... } - -[GlobalSetup(Targets = new[] { nameof(BenchmarkB), nameof(BenchmarkC) })] -public void SetupBC() { ... } -``` - -`[GlobalCleanup]` runs once after all iterations. Use it to dispose resources (files, connections) created during setup. - -**Note**: when `[MemoryRandomization]` is enabled, BDN re-runs `[GlobalCleanup]` and `[GlobalSetup]` after every iteration (overriding the normal once-only behavior). See [references/bdn-internals-and-tuning.md](references/bdn-internals-and-tuning.md) for details. - -### IterationSetup / IterationCleanup - -A method marked `[IterationSetup]` runs before every iteration. Use it only when the benchmark mutates state that must be reset — for example, sorting an array in-place. - -**Critical constraint**: when `[IterationSetup]` or `[IterationCleanup]` is used, BDN defaults to `InvocationCount=1` and `UnrollFactor=1` (unless explicitly overridden). This means the entire iteration is a single invocation, so the operation should be long enough (generally hundreds of milliseconds or more) for a single-invocation measurement to be reliable — with only one invocation, OS scheduling jitter and timer resolution become a significant fraction of the measured time. - -```csharp -[Params(10_000_000)] // large enough for single-invocation measurement -public int Size { get; set; } - -private int[] _data, _scratch; - -[GlobalSetup] -public void Setup() => _data = Enumerable.Range(0, Size).Reverse().ToArray(); - -[IterationSetup] -public void ResetArray() => Array.Copy(_data, _scratch = new int[Size], Size); - -[Benchmark] -public void Sort() => Array.Sort(_scratch); -``` - -**If `[GlobalSetup]` is sufficient, do not use `[IterationSetup]`.** It adds overhead and constrains the measurement. - -## OperationsPerInvoke - -When part of the benchmark setup cannot be moved to `[GlobalSetup]` — typically because it involves a stack-only type like `Span` — use `OperationsPerInvoke` to amortize the setup cost by performing multiple logical operations per invocation. - -```csharp -private byte[] _array = new byte[18]; - -[Benchmark(OperationsPerInvoke = 16)] -public Span Slice() -{ - Span span = new Span(_array); // setup: can't go in GlobalSetup (stack-only) - - // 16 operations, unrolled without a loop - span = span.Slice(1); span = span.Slice(1); span = span.Slice(1); span = span.Slice(1); - span = span.Slice(1); span = span.Slice(1); span = span.Slice(1); span = span.Slice(1); - span = span.Slice(1); span = span.Slice(1); span = span.Slice(1); span = span.Slice(1); - span = span.Slice(1); span = span.Slice(1); span = span.Slice(1); span = span.Slice(1); - - return span; -} -``` - -BDN divides the measured time by `OperationsPerInvoke`, so the reported result reflects a single `Slice` operation with the `Span` creation cost amortized. The operations are manually unrolled (not in a loop) to avoid loop overhead affecting the measurement. - -## Avoiding loops - -BDN determines how many times to invoke the benchmark method per iteration automatically (the pilot stage). Adding a manual loop inside the benchmark is unnecessary and harmful: - -```csharp -// Wrong — manual loop adds loop overhead and hides per-operation variance -[Benchmark] -public int ParseLoop() -{ - int result = 0; - for (int i = 0; i < 1000; i++) - result += int.Parse("12345"); - return result; -} - -// Correct — BDN handles invocation count -[Benchmark] -public int Parse() => int.Parse("12345"); -``` - -The exception is `OperationsPerInvoke` — when per-invocation setup cannot be avoided, repeating the operation inside the method and declaring the count lets BDN divide the result correctly. - -## No side effects - -Benchmarks should be idempotent — running the method N times should produce the same performance characteristics as running it once. A benchmark that grows a list on every invocation violates this: - -```csharp -// Wrong — list grows with every invocation, later calls are slower -List _numbers = new(); - -[Benchmark] -public void Add() => _numbers.Add(12345); -``` - -If the operation inherently mutates state (e.g., `Array.Sort`), use `[IterationSetup]` to reset state between iterations, with input large enough for reliable single-invocation measurement. - -## Async benchmarks - -BDN natively supports benchmark methods that return `Task`, `Task`, `ValueTask`, or `ValueTask`. BDN awaits the result automatically — there is no special attribute or configuration needed: - -```csharp -[Benchmark] -public async Task ReadAsync() -{ - using var stream = new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: true); - var buffer = new byte[4096]; - return await stream.ReadAsync(buffer); -} -``` - -**Async setup/cleanup**: `[GlobalSetup]` and `[GlobalCleanup]` methods can also return `Task` or `ValueTask` — BDN awaits them automatically. `[IterationSetup]` and `[IterationCleanup]` do **not** support async return types; they must be synchronous. - -**When NOT to use async**: if the operation being benchmarked is synchronous, do not wrap it in `async`/`await`. The async state machine adds overhead that would be included in the measurement: - -```csharp -// Wrong — adds async state machine overhead to a synchronous operation -[Benchmark] -public async Task ParseAsync() => await Task.FromResult(int.Parse("12345")); - -// Correct — benchmark the synchronous method directly -[Benchmark] -public int Parse() => int.Parse("12345"); -``` - -## Deferred execution - -Returning `IEnumerable`, `IQueryable`, or `Lazy` from a benchmark measures only the creation of the deferred sequence — not its execution. This is almost always a bug: - -```csharp -// Wrong — measures only the creation of the LINQ query object, not its execution -[Benchmark] -public IEnumerable WhereQuery() => _numbers.Where(n => n > 50); - -// Correct — materialize the result so the query actually executes -[Benchmark] -public List WhereQuery() => _numbers.Where(n => n > 50).ToList(); -``` - -BDN includes a `DeferredExecutionValidator` that detects this mistake and raises a validation error, preventing the benchmark from running. To fix it, either materialize the result (`.ToList()`, `.ToArray()`) or consume it manually using the `.Consume()` extension method: - -```csharp -private Consumer _consumer = new(); - -[Benchmark] -public void WhereQuery() => _numbers.Where(n => n > 50).Consume(_consumer); -``` - -## Constant folding - -The JIT can evaluate expressions at compile time when all inputs are constants or literals. If a benchmark operates on constant inputs, the JIT may fold the computation into a precomputed result, and the benchmark measures nothing: - -```csharp -// Wrong — JIT can compute Math.Sqrt(144.0) at compile time -[Benchmark] -public double Sqrt() => Math.Sqrt(144.0); - -// Correct — field value is not a compile-time constant -private double _value = 144.0; - -[Benchmark] -public double Sqrt() => Math.Sqrt(_value); -``` - -Store inputs in fields, `[Params]`, or `[Arguments]` — never as literals or `const` values in the benchmark method. - -## Randomness and reproducibility - -When benchmarks use generated input data, use a fixed seed so results are comparable across runs: - -```csharp -[GlobalSetup] -public void Setup() -{ - var rng = new Random(42); // fixed seed - _data = new byte[Size]; - rng.NextBytes(_data); -} -``` - -## Benchmark class constraints - -BDN generates source code for a derived type from the benchmark class, which is compiled as part of its generated project. This imposes constraints: -- The class must be `public` -- The class must not be `sealed`, `static`, or `abstract` -- The class must be a `class`, not a `struct` or `ref struct` -- Benchmark methods must be `public` and instance (not `static`) - -## Parameterization summary - -| Feature | Target | Use when | -|---------|--------|----------| -| `[Params]` | Field/Property | Values needed in setup; applies to all benchmarks in the class | -| `[ParamsSource]` | Field/Property | Dynamic or complex values needed in setup | -| `[ParamsAllValues]` | Field/Property | Enum or bool — test every possible value | -| `[Arguments]` | Method | Inline values for a specific benchmark method | -| `[ArgumentsSource]` | Method | Dynamic or complex values for a specific benchmark method | -| `[GenericTypeArguments]` | Class | Vary type parameters (e.g., value type vs reference type) | - -`[Params]` applies to all benchmarks in the class. If different benchmarks need different parameter ranges, split them into separate classes. - -`[Arguments]` and `[ArgumentsSource]` are method-specific and their initialization time is excluded from the measurement. `[ArgumentsSource]` methods return `IEnumerable` for single-parameter benchmarks, or `IEnumerable` for multi-parameter benchmarks (each array is one set of arguments). `[ParamsSource]` methods return `IEnumerable` (each element is a single value assigned to the field/property). - -```csharp -// Single-parameter: IEnumerable -[Benchmark] -[ArgumentsSource(nameof(Inputs))] -public int Parse(string text) => int.Parse(text); - -public IEnumerable Inputs() -{ - yield return "12345"; - yield return "999999999"; - yield return "-42"; -} - -// Multi-parameter: IEnumerable -[Benchmark] -[ArgumentsSource(nameof(Inputs))] -public bool TryParse(string text, NumberStyles style) => int.TryParse(text, style, null, out _); - -public IEnumerable Inputs() -{ - yield return new object[] { "12345", NumberStyles.Integer }; - yield return new object[] { "0xFF", NumberStyles.HexNumber }; -} -``` - -`[ParamsSource]` works the same way but targets a field/property and applies to all benchmarks in the class: - -```csharp -[ParamsSource(nameof(Sizes))] -public int N; - -public IEnumerable Sizes() => new[] { 100, 1_000, 10_000 }; -``` - -`[GenericTypeArguments]` varies type parameters on a generic benchmark class. Each attribute creates a separate closed generic type that BDN runs independently: - -```csharp -[GenericTypeArguments(typeof(int))] -[GenericTypeArguments(typeof(string))] -public class CollectionBenchmark -{ - private List _list; - - [GlobalSetup] - public void Setup() => _list = new List(Enumerable.Repeat(default(T)!, 1000)); - - [Benchmark] - public bool Contains() => _list.Contains(default!); -} -``` diff --git a/plugins/dotnet-maui/skills/maui-collectionview/SKILL.md b/plugins/dotnet-maui/skills/maui-collectionview/SKILL.md deleted file mode 100644 index 2158a64325..0000000000 --- a/plugins/dotnet-maui/skills/maui-collectionview/SKILL.md +++ /dev/null @@ -1,470 +0,0 @@ ---- -name: maui-collectionview -description: > - Guidance for implementing CollectionView in .NET MAUI apps — data display, - layouts (list & grid), selection, grouping, scrolling, empty views, templates, - incremental loading, swipe actions, and pull-to-refresh. - USE FOR: "CollectionView", "list view", "grid layout", "data template", - "item template", "grouping", "pull to refresh", "incremental loading", - "swipe actions", "empty view", "selection mode", "scroll to item", - displaying scrollable data, replacing ListView. - DO NOT USE FOR: simple static layouts without scrollable data (use Grid or - StackLayout), map pin lists (use Microsoft.Maui.Controls.Maps), table-based - data entry forms, non-MAUI list controls, CarouselView or BindableLayout - questions, platform-specific handler or renderer customization, diagnosing - CollectionView bugs in the MAUI framework itself, or general MVVM/binding - questions that merely happen to mention a list (use maui-data-binding). -license: MIT ---- - -# CollectionView — .NET MAUI - -`CollectionView` is the primary control for displaying scrollable lists and grids of data in .NET MAUI. It replaces `ListView` with better performance, flexible layouts, and no `ViewCell` requirement. - -## When to Use - -- Displaying a scrollable list or grid of data items -- Binding a collection of objects to a templated item layout -- Adding selection (single or multiple), grouping, or pull-to-refresh -- Implementing infinite scroll / incremental loading -- Showing swipe actions on list items -- Displaying an empty state when no data is available - -## When Not to Use - -- Static layouts with a fixed number of items — use `Grid` or `StackLayout` directly -- Map pin lists — use the `Microsoft.Maui.Controls.Maps` NuGet package -- Table-based data entry forms — use standard form controls -- Simple text-only lists with no interaction — consider `BindableLayout` on a `StackLayout` - -## Scope Control — Answer Only What Was Asked - -This skill is a **reference you consult**, not a checklist you apply. Most requests -need one or two sections from it. Pulling in the rest makes the answer worse. - -**Stop conditions — do NOT act when:** - -- **The user asked a narrow question.** Answer that question only. Do not append - grouping, swipe actions, empty views, snap points, or performance tips that - were not asked about. -- **The user's existing code already works.** Do not rewrite working markup to - match the examples here. Point out a concrete defect; if there is none, say so - and answer the question that was asked. -- **The change is stylistic.** Renaming, reordering attributes, or restructuring - a template that already behaves correctly is churn, not a fix. -- **The control isn't `CollectionView`.** `CarouselView`, `BindableLayout`, and - `ListView`-in-maintenance code have different rules. Do not rewrite `ListView` - code the user did not ask about — but if they ask *which* control to use, or are - migrating from Xamarin.Forms, recommend `CollectionView` (see - [Migrating from ListView](#migrating-from-listview)). -- **The problem is really a binding, DI, or navigation problem** that happens to - involve a list — defer to `maui-data-binding`, `maui-dependency-injection`, or - `maui-shell-navigation`. - -**The API sections below are a reference, not a checklist — offer them only when -relevant.** Four rules are non-negotiable, because violating them produces code that -does not work or silently loses compile-time checking: - -1. Never use `ViewCell` as a `DataTemplate` root in `CollectionView`. -2. Use `ObservableCollection` when the list mutates after first render. -3. Mutate the bound collection on the UI thread. -4. Set `x:DataType` on every `DataTemplate` (and on the page root) for compiled bindings. - -Everything else — sizing strategy, snap points, header/footer, empty views — is -optional and should be offered only when it addresses the user's actual problem. - -## Inputs - -- A data source (typically `ObservableCollection`) bound to `ItemsSource` -- A `DataTemplate` defining how each item renders -- Optional: layout configuration, selection mode, grouping model, empty view - -## Basic Setup - -A complete, copy-pasteable page. Two things are load-bearing: the `xmlns:models` -declaration that every `x:DataType="models:Item"` in this skill assumes, and the -**root `x:DataType`** — without it the outer `ItemsSource` binding is not compiled: - -```xml - - - - - - - - - - - - - - -``` - -Later snippets show only the `CollectionView` element. When you hand a snippet to a -user, include the matching `xmlns:` declaration for any prefix it uses, or the XAML -will not compile. - -The inline `` above keeps the example self-contained. In -an app that uses dependency injection, register the ViewModel instead and assign it -through constructor injection (`BindingContext = vm;`) — see the -**maui-dependency-injection** skill. - -**Key rules:** - -- Bind `ItemsSource` to an `ObservableCollection` so the UI updates on add/remove. -- Each item template root must be a `Layout` or `View` — **never use `ViewCell`**. -- Always set `x:DataType` on `DataTemplate` for compiled bindings. - -## Layouts - -Set `ItemsLayout` to control arrangement. Default is `VerticalList`. - -| Layout | XAML value | -|---|---| -| Vertical list | `VerticalList` (default) | -| Horizontal list | `HorizontalList` | -| Vertical grid | `GridItemsLayout` with `Orientation="Vertical"` | -| Horizontal grid | `GridItemsLayout` with `Orientation="Horizontal"` | - -### Grid Layout - -```xml - - - - - - - - - - - - - - -``` - -### Horizontal List - -```xml - -``` - -## Selection - -### Selection Mode - -| Mode | Property to bind | Binding mode | -|---|---|---| -| `None` | — | — | -| `Single` | `SelectedItem` | `TwoWay` | -| `Multiple` | `SelectedItems` | `OneWay` | - -```xml - -``` - -For `Multiple` selection, bind `SelectedItems` (type `IList`): - -```xml - -``` - -### Selected Visual State - -Highlight selected items using `VisualStateManager`: - -```xml - - - - - - - - - - - - - - - - - - - - -``` - -## Grouping - -1. Create a group class inheriting from `List`: - -```csharp -public class AnimalGroup : List -{ - public string Name { get; } - public AnimalGroup(string name, List animals) : base(animals) - { - Name = name; - } -} -``` - -2. Bind to `ObservableCollection` and set `IsGrouped="True"`: - -```xml - - - - - - - - - - -``` - -## Pull-to-Refresh - -Wrap `CollectionView` in a `RefreshView`. Set `IsRefreshing` back to `false` when done: - -```xml - - - -``` - -## Incremental Loading (Infinite Scroll) - -```xml - -``` - -> ⚠️ **Do NOT use with non-virtualizing layouts.** `LinearItemsLayout` and `GridItemsLayout` support virtualization. Using `BindableLayout` on a `StackLayout` as an alternative to `CollectionView` has no virtualization, which triggers infinite threshold-reached events. - -## SwipeView — Binding from Inside DataTemplate - -Commands inside a `DataTemplate` can't directly reach your ViewModel. Use `RelativeSource AncestorType`: - -```xml - - - - - - - - - - - - - -``` - -## EmptyView - -Shown when `ItemsSource` is empty or null. - -```xml - -``` - -For a custom empty view, wrap in `ContentView`: - -```xml - - - - - - - - - -``` - -## Headers and Footers - -```xml - - - - - - -``` - -Use `HeaderTemplate` / `FooterTemplate` when headers or footers are data-bound. - -## Scrolling - -### ScrollTo - -Programmatically scroll by index or item: - -```csharp -// Scroll to index -collectionView.ScrollTo(index: 10, position: ScrollToPosition.Center, animate: true); - -// Scroll to item -collectionView.ScrollTo(item: myItem, position: ScrollToPosition.MakeVisible, animate: true); -``` - -| ScrollToPosition | Behavior | -|---|---| -| `MakeVisible` | Scrolls just enough to make the item visible | -| `Start` | Scrolls item to the start of the viewport | -| `Center` | Scrolls item to the center of the viewport | -| `End` | Scrolls item to the end of the viewport | - -### Snap Points - -```xml - - - -``` - -- `SnapPointsType`: `None`, `Mandatory`, `MandatorySingle` -- `SnapPointsAlignment`: `Start`, `Center`, `End` - -## Migrating from ListView - -`ListView` still compiles, but **as of .NET 10** it is marked `[Obsolete]` -("*ListView is deprecated. Please use CollectionView instead.*"). It is **not** -obsolete on .NET 9 and earlier, so check the project's target framework before -describing it as deprecated. **If the user asks -which control to use, or is migrating from Xamarin.Forms, recommend -`CollectionView`** — it is faster, needs no `ViewCell`, and supports flexible -layouts. What to avoid is silently rewriting `ListView` code the user did not ask -you to touch. - -| `ListView` | `CollectionView` equivalent | -|---|---| -| `ViewCell` template root | Any `View`/`Layout` root — **`ViewCell` is not supported** | -| `ItemSelected` event | `SelectionChanged` event, or `SelectionChangedCommand` | -| `ItemTapped` event | A `TapGestureRecognizer` in the item template — `SelectionChanged` only fires when the selection *changes*, so it will not re-fire on tapping the already-selected item | -| `IsPullToRefreshEnabled` + `Refreshing` | Wrap the `CollectionView` in a `RefreshView` | -| `IsGroupingEnabled` | `IsGrouped` | -| `HasUnevenRows="True"` | Default `ItemSizingStrategy="MeasureAllItems"` | -| `RowHeight` (fixed height) | Set the height in the item template. `MeasureFirstItem` only reuses the first item's measured size — it is not an explicit row height | -| `SeparatorVisibility` / `SeparatorColor` | **No equivalent** — draw a `BoxView`/`Border` in the item template | - -The missing separator API is the most common migration surprise: `CollectionView` -has no built-in separators, so add one to the template yourself. - -## Performance Tips - -Apply these only when the user reports a performance problem or explicitly asks -about performance — they are not a default checklist. - -- **Use `MeasureFirstItem`** for uniform item sizes — significantly faster than the default - `MeasureAllItems`, which measures every item individually. Set it on the `CollectionView` - itself (it is declared on `StructuredItemsView`), **not** on `LinearItemsLayout` / - `GridItemsLayout`: - ```xml - - - - - - - - - - ``` - **When `MeasureFirstItem` is the wrong choice** — keep the default `MeasureAllItems` if: - - Items vary in height (wrapping text, optional rows, images of differing aspect) — the - first item's size is applied to all, so the rest are clipped or stretched. - - A `DataTemplateSelector` returns different templates — the first item won't represent - the others. - - The first item is atypical (a header-like or "featured" row) — every item inherits its - size. Fixing this by reordering data is a smell; use `MeasureAllItems` instead. - - Item size depends on runtime data that isn't loaded yet when the first item is measured. -- **Use `ObservableCollection` when the list mutates after first render.** It implements - `INotifyCollectionChanged`, so in-place `Add`/`Remove`/`Insert` update the UI incrementally. - A `List` is fine for a list that never changes after it is bound. Note that *replacing* - `ItemsSource` re-renders everything regardless of the collection type — so mutate the bound - collection in place rather than reassigning it. -- **Update collections on the UI thread** — `MainThread.BeginInvokeOnMainThread(() => Items.Add(item))`. - -## Common Pitfalls - -| Issue | Fix | -|---|---| -| UI doesn't update when items change | Use `ObservableCollection`, not `List`. | -| App crashes or blank items | **Never use `ViewCell`** — use `Grid`, `StackLayout`, or any `View` as template root. | -| Items disappear or layout breaks | Always update `ItemsSource` and the collection on the **UI thread** (`MainThread.BeginInvokeOnMainThread`). | -| Incremental loading fires endlessly | Don't use `StackLayout` as layout; use `LinearItemsLayout` or `GridItemsLayout`. | -| EmptyView doesn't render correctly | Wrap custom empty views in `ContentView`. | -| Poor scroll performance | Use `MeasureFirstItem` sizing strategy for uniform item sizes. | -| `ItemSizingStrategy` doesn't compile | It is declared on `StructuredItemsView` — set it on ``, not on `` / ``. | -| Items clipped or stretched | `MeasureFirstItem` assumes uniform item size. Use the default `MeasureAllItems` for variable-height items. | -| Selected state not visible | Add `VisualState Name="Selected"` to the item template root element. | -| Binding errors in SwipeView commands | Use `RelativeSource AncestorType` to reach the ViewModel from inside the item template. | - -## Validation - -Before returning CollectionView markup you wrote or edited, confirm: - -- [ ] The `DataTemplate` root is a `View`/`Layout` — **not** `ViewCell`. -- [ ] `DataTemplate` declares `x:DataType` for compiled bindings. -- [ ] `ItemsSource` is bound to `ObservableCollection` if the list mutates. -- [ ] `ItemSizingStrategy` (if used) is on ``, not on the layout. -- [ ] `Multiple` selection binds `SelectedItems`; `Single` binds `SelectedItem` (`TwoWay`). -- [ ] `RefreshView.IsRefreshing` is set back to `false` when the refresh completes. -- [ ] The answer covers **only** what the user asked — no unrequested sections. - -## References - -- [CollectionView overview](https://learn.microsoft.com/dotnet/maui/user-interface/controls/collectionview/) -- [CollectionView layout](https://learn.microsoft.com/dotnet/maui/user-interface/controls/collectionview/layout) -- [CollectionView selection](https://learn.microsoft.com/dotnet/maui/user-interface/controls/collectionview/selection) -- [CollectionView grouping](https://learn.microsoft.com/dotnet/maui/user-interface/controls/collectionview/grouping) -- [CollectionView scrolling](https://learn.microsoft.com/dotnet/maui/user-interface/controls/collectionview/scrolling) -- [CollectionView EmptyView](https://learn.microsoft.com/dotnet/maui/user-interface/controls/collectionview/emptyview) diff --git a/plugins/dotnet-maui/skills/maui-collectionview/references/collectionview-api.md b/plugins/dotnet-maui/skills/maui-collectionview/references/collectionview-api.md deleted file mode 100644 index 2b8af5701b..0000000000 --- a/plugins/dotnet-maui/skills/maui-collectionview/references/collectionview-api.md +++ /dev/null @@ -1,241 +0,0 @@ -# CollectionView API Reference - -## Layouts - -Set `ItemsLayout` to control arrangement. Default is `VerticalList`. - -| Layout | XAML value | -|---|---| -| Vertical list | `VerticalList` (default) | -| Horizontal list | `HorizontalList` | -| Vertical grid | `GridItemsLayout` with `Orientation="Vertical"` | -| Horizontal grid | `GridItemsLayout` with `Orientation="Horizontal"` | - -### Grid layout - -```xml - - - - - -``` - -### Horizontal list - -```xml - -``` - -## ItemSizingStrategy - -Controls how items are measured. Set on the **`CollectionView` element itself** — it is declared on `StructuredItemsView`, **not** on `ItemsLayout`. - -| Value | Behavior | -|---|---| -| `MeasureAllItems` | Measures every item individually (default). Accurate but slower for heterogeneous sizes. | -| `MeasureFirstItem` | Measures only the first item and applies that size to all. Much faster for uniform items. | - -```xml - - -``` - -```xml - - - - -``` - -## ItemSpacing - -Use `ItemSpacing` on `LinearItemsLayout` or `VerticalItemSpacing` / `HorizontalItemSpacing` on `GridItemsLayout`: - -```xml - - - -``` - -## Headers and Footers - -Supports string, view, or templated: - -```xml - - - - - - - - - - -``` - -Use `HeaderTemplate` / `FooterTemplate` when headers/footers are data-bound. - -## Selection - -### Selection mode - -| Mode | Property to bind | Binding mode | -|---|---|---| -| `None` | — | — | -| `Single` | `SelectedItem` | `TwoWay` | -| `Multiple` | `SelectedItems` | `OneWay` | - -```xml - -``` - -For `Multiple` selection, bind `SelectedItems` (type `IList`): - -```xml - -``` - -### Selected visual state - -Highlight selected items using `VisualStateManager`: - -```xml - - - - - - - - - - - - - - - - - - - - -``` - -## Grouping - -1. Create a group class inheriting from `List`: - -```csharp -public class AnimalGroup : List -{ - public string Name { get; } - public AnimalGroup(string name, List animals) : base(animals) - { - Name = name; - } -} -``` - -2. Bind to `ObservableCollection` and set `IsGrouped="True"`: - -```xml - - - - - - - - - - - - - - -``` - -## EmptyView - -Shown when `ItemsSource` is empty or null. - -```xml - - - - - - - - - - - - - -``` - -You can also use `EmptyViewTemplate` with a `DataTemplateSelector` to swap empty views based on state. - -## Scrolling - -### ScrollTo - -Programmatically scroll by index or item: - -```csharp -// Scroll to index -collectionView.ScrollTo(index: 10, position: ScrollToPosition.Center, animate: true); - -// Scroll to item -collectionView.ScrollTo(item: myItem, position: ScrollToPosition.MakeVisible, animate: true); -``` - -| ScrollToPosition | Behavior | -|---|---| -| `MakeVisible` | Scrolls just enough to make the item visible | -| `Start` | Scrolls item to the start of the viewport | -| `Center` | Scrolls item to the center of the viewport | -| `End` | Scrolls item to the end of the viewport | - -### Snap points - -Control snap behavior after scrolling: - -```xml - - - -``` - -- `SnapPointsType`: `None`, `Mandatory`, `MandatorySingle` -- `SnapPointsAlignment`: `Start`, `Center`, `End` diff --git a/plugins/dotnet-msbuild/skills/check-bin-obj-clash/SKILL.md b/plugins/dotnet-msbuild/skills/check-bin-obj-clash/SKILL.md deleted file mode 100644 index 8d1007cfde..0000000000 --- a/plugins/dotnet-msbuild/skills/check-bin-obj-clash/SKILL.md +++ /dev/null @@ -1,315 +0,0 @@ ---- -name: check-bin-obj-clash -description: "Detects MSBuild projects with conflicting OutputPath or IntermediateOutputPath. USE FOR: builds failing with 'Cannot create a file when that file already exists', 'The process cannot access the file because it is being used by another process', intermittent build failures that succeed on retry, or missing/overwritten outputs in multi-project or multi-targeting builds where bin/obj (or project.assets.json) collide. Common causes: shared OutputPath, missing AppendTargetFrameworkToOutputPath, extra global properties (e.g. PublishReadyToRun), or SetTargetFramework on a ProjectReference to a single-targeting project. DO NOT USE FOR: file access errors unrelated to MSBuild (OS-level locking), single-project single-TFM builds, non-MSBuild build systems." -license: MIT ---- - -# Detecting OutputPath and IntermediateOutputPath Clashes - -## Overview - -This skill helps identify when multiple MSBuild project evaluations share the same `OutputPath` or `IntermediateOutputPath`. This is a common source of build failures including: - -- File access conflicts during parallel builds -- Missing or overwritten output files -- Intermittent build failures -- "File in use" errors -- **NuGet restore errors like `Cannot create a file when that file already exists`** - this strongly indicates multiple projects share the same `IntermediateOutputPath` where `project.assets.json` is written - -Clashes can occur between: -- **Different projects** sharing the same output directory -- **Multi-targeting builds** (e.g., `TargetFrameworks=net8.0;net9.0`) where the path doesn't include the target framework -- **Multiple solution builds** where the same project is built from different solutions in a single build - -**Note:** Project instances with `BuildProjectReferences=false` should be **ignored** when analyzing clashes - these are P2P reference resolution builds that only query metadata (via `GetTargetPath`) and do not actually write to output directories. - -## When to Use This Skill - -**Invoke this skill immediately when you see:** -- `Cannot create a file when that file already exists` during NuGet restore -- `The process cannot access the file because it is being used by another process` -- Intermittent build failures that succeed on retry -- Missing output files or unexpected overwriting - -## Step 1: Generate a Binary Log - -Use the `binlog-generation` skill to generate a binary log with the correct naming convention. - -## Primary workflow — binlog MCP - -The MCP server exposes structured tools for inspecting a `.binlog` without -parsing text logs. Call them directly instead of replaying the binlog to a text -file. Call `tools/list` for the MCP first if you are unsure which tools are available. - -**Important constraints:** -- The `.binlog` file is a **binary format** — do NOT try to `cat`, `head`, `strings`, or read it directly. Use only the MCP tools to query it. -- **Synthesize findings as you go.** Do not spend all available time investigating — once you have enough evidence, present your conclusions. - -### Step 2: Get an overview and list projects - -Use the MCP overview and projects tools to understand the build and list all projects that participated. - -### Step 3: Check evaluations and global properties - -Use the MCP `evaluations` and `evaluation_global_properties` tools to find all evaluations per project. Look for: -- Multiple evaluations for the same project (indicates multi-targeting or multiple build configurations) -- Differing global properties between evaluations (`TargetFramework`, `Configuration`, `RuntimeIdentifier`, `SolutionFileName`, `PublishReadyToRun`, etc.) - -### Step 4: Get output paths for each evaluation - -Use the MCP properties tool to query `OutputPath`, `IntermediateOutputPath`, `BaseOutputPath`, and `BaseIntermediateOutputPath` for each project evaluation. - -### Step 5: Check for double writes - -Use the MCP double_writes tool if available — it directly detects files written by multiple project instances. - -### Step 6: Identify clashes - -Compare the `OutputPath` and `IntermediateOutputPath` values across all evaluations: -1. **Normalize paths** - Convert to absolute paths and normalize separators -2. **Group by path** - Find evaluations that share the same OutputPath or IntermediateOutputPath -3. **Filter out non-build evaluations** - Exclude `BuildProjectReferences=false` instances (P2P queries) -4. **Report clashes** - Any group with more than one evaluation indicates a clash - -## Fallback workflow — text-log replay (when MCP is unavailable) - -Use this only when the MCP server cannot be started. - -Replay the binlog to a diagnostic text log, then grep for the same signals the MCP tools surface: - -```bash -dotnet msbuild build.binlog -noconlog -fl -flp:v=diag;logfile=full.log -``` - -Then extract the clash signals: - -- **Projects & evaluations** — list evaluation starts and count them per project: `grep 'Evaluation started' full.log | grep -oiE '"[^"]+\.[a-z]+proj"' | sort | uniq -c`. Matching the full **quoted path** keeps same-named projects in different directories distinct (and tolerates spaces in paths); a path with a count ≥ 2 was evaluated more than once (multi-targeting or extra global properties). (`grep -c` alone only totals evaluations across the whole log, so it can't reveal per-project duplication.) -- **Output paths** — `grep -iE 'OutputPath[[:space:]]*=|IntermediateOutputPath[[:space:]]*=|BaseOutputPath[[:space:]]*=|BaseIntermediateOutputPath[[:space:]]*=' full.log | sort -u`, or query a project directly: `dotnet msbuild MyProject.csproj -getProperty:OutputPath` (and `IntermediateOutputPath`, `BaseIntermediateOutputPath`). -- **Distinguishing global properties** — `grep -iE 'TargetFramework|Configuration|Platform|RuntimeIdentifier|SolutionFileName|PublishReadyToRun' full.log`. See the [Global Properties to Check](#global-properties-to-check-when-comparing-evaluations) table for which affect the path and which just fork a redundant instance. -- **Corroborating evidence (optional)** — `grep 'Target "CopyFilesToOutputDirectory"' full.log` plus `grep 'SkipUnchangedFiles' full.log` show a second instance writing (or skipping a masked write) to the same path; a long vs ~0 ms `CoreCompile` distinguishes the real build from a redundant instance. - -**Then identify clashes:** normalize paths to absolute, group evaluations by `OutputPath` and by `IntermediateOutputPath`, and exclude `BuildProjectReferences=false` (P2P queries) — plus, for `OutputPath` only, `MSBuildRestoreSessionId` restore evaluations. Any group with more than one remaining evaluation is a clash. - -## Common Causes and Fixes - -### Multi-targeting without TargetFramework in path - -**Problem:** Project uses `TargetFrameworks` but OutputPath doesn't vary by framework. - -```xml - -bin\$(Configuration)\ -``` - -**Fix:** Include TargetFramework in the path: - -```xml - -bin\$(Configuration)\$(TargetFramework)\ -``` - -Or rely on SDK defaults which handle this automatically: - -```xml -true -true -``` - -### Shared output directory across projects (CANNOT be fixed with AppendTargetFramework) - -**Problem:** Multiple projects explicitly set the same `BaseOutputPath` or `BaseIntermediateOutputPath`. - -```xml - -..\SharedOutput\ -..\SharedObj\ - - -..\SharedOutput\ -..\SharedObj\ -``` - -**IMPORTANT:** Even with `AppendTargetFrameworkToOutputPath=true`, this will still clash! .NET writes certain files directly to the `IntermediateOutputPath` without the TargetFramework suffix, including: - -- `project.assets.json` (NuGet restore output) -- Other NuGet-related files - -This causes errors like `Cannot create a file when that file already exists` during parallel restore. - -**Fix:** Each project MUST have a unique `BaseIntermediateOutputPath`. Do not share intermediate output directories across projects: - -```xml - -..\obj\ProjectA\ - - -..\obj\ProjectB\ -``` - -Or simply use the SDK defaults which place `obj` inside each project's directory. - -### RuntimeIdentifier builds clashing - -**Problem:** Building for multiple RIDs without RID in path. - -**Fix:** Ensure RuntimeIdentifier is in the path: - -```xml -true -``` - -### Multiple solutions building the same project - -**Problem:** A single build invokes multiple solutions (e.g., via MSBuild task or command line) that include the same project. Each solution build evaluates and builds the project independently, with different `Solution*` global properties that don't affect the output path. - -**How to detect:** Compare `SolutionFileName` and `CurrentSolutionConfigurationContents` across evaluations for the same project. Different values indicate multi-solution builds. For example: - -| Property | Eval from Solution A | Eval from Solution B | -|---|---|---| -| `SolutionFileName` | `BuildAnalyzers.sln` | `Main.slnx` | -| `CurrentSolutionConfigurationContents` | 1 project entry | ~49 project entries | -| `OutputPath` | `bin\Release\netstandard2.0\` | `bin\Release\netstandard2.0\` ← **clash** | - -**Example:** A repo build script builds `BuildAnalyzers.sln` then `Main.slnx`, and both solutions include `SharedAnalyzers.csproj`. Both builds write to `bin\Release\netstandard2.0\`. The first build compiles; the second skips compilation but still runs `CopyFilesToOutputDirectory`. - -**Fix:** Options include: -1. **Consolidate solutions** - Ensure each project is only built from one solution in a single build -2. **Use different configurations** - Build solutions with different `Configuration` values that result in different output paths -3. **Exclude duplicate projects** - Use solution filters or conditional project inclusion to avoid building the same project twice - -### Extra global properties creating redundant project instances - -**Problem:** A project is built multiple times within the same solution due to extra global properties (e.g., `PublishReadyToRun=false`) that create distinct MSBuild project instances. These properties don't affect output paths but prevent MSBuild from caching results across instances, causing redundant target execution. - -**How to detect:** Compare global properties across evaluations for the same project within the same solution (same `SolutionFileName`). Look for properties that differ but don't contribute to path differentiation: - -| Property | Eval A (from Razor.slnx) | Eval B (from Razor.slnx) | -|---|---|---| -| `PublishReadyToRun` | *(not set)* | `false` | -| `OutputPath` | `bin\Release\netstandard2.0\` | `bin\Release\netstandard2.0\` ← **clash** | - -This is particularly wasteful for projects where the extra property has no effect (e.g., `PublishReadyToRun` on a `netstandard2.0` class library that doesn't use ReadyToRun compilation). - -**Fix:** Options include: -1. **Remove the extra global property** - Investigate which parent target/task is injecting the property and prevent it from being passed to projects that don't need it -2. **Use `RemoveGlobalProperties` metadata** - On `ProjectReference` items, use `RemoveGlobalProperties="PublishReadyToRun"` to strip the property before building the referenced project -3. **Condition the property** - Only set the property on projects that actually use it (e.g., only for executable projects, not class libraries) - -### Explicit `` Build/Publish with extra global properties (self or cross-project) - -**Problem:** A target uses the `` task to build or publish a project with an extra global property, most commonly a "publish-on-build" target. The offending call can be in the target project itself **or in another project** that consumes it (e.g. a test or layout project publishing a tool): - -```xml - - - - - - - -``` - -Either way this forks a distinct instance of the target project (`path` + `{_IsPublishing=true}`) that shares the same `OutputPath`/`IntermediateOutputPath` as the instance the solution/graph already builds. Both write the same files — for NativeAOT this includes the `*.sourcelink` intermediate, which produces `SourceLinkWriter` / "file in use" failures under parallel builds. - -**How to detect:** Follow the Primary workflow above — the `evaluations` and `evaluation_global_properties` tools surface two evaluations of the target project that share the same `OutputPath`/`IntermediateOutputPath` but differ only by a path-neutral publish flag such as `_IsPublishing`, and the `double_writes` tool flags the resulting shared-file writes directly. To tell case (a) from (b), see which project the extra `{_IsPublishing=true}` evaluation runs *under* in the build tree (from the overview/projects tools): the target project itself for (a), or a consumer project that invoked the `` task for (b). - -**Fix:** Depends on where the call lives: - -- **Same project (a):** you can't strip the property with `RemoveGlobalProperties` (the project injects it on itself). Set the flag as a **static** (non-global) property and run the target in the **same** instance via `DependsOnTargets`/`CallTarget`, with a guard against a target cycle when publish is the entry point: - -```xml - - <_PublishWasInvokedDirectly Condition="'$(_IsPublishing)' == 'true'">true - <_IsPublishing>true - - -``` - -- **Cross-project (b):** the consumer must not fork the producer with path-neutral global properties. Make the producer publish as part of its own build (the (a) fix in *its* project), then have the consumer **sequence** it and read its output instead of re-publishing it: - -```xml - - - - -``` - -See the `msbuild-antipatterns` skill (AP-22) for the authoring-time smell and rationale. - -### `SetTargetFramework` re-injecting a single-targeting project's own TFM on a `ProjectReference` - -**Problem:** A `ProjectReference` sets `SetTargetFramework="TargetFramework="` metadata pointing at a **single-targeting** project (one that uses singular ``, not ``), where the injected `` **equals the TFM the project already targets**. `SetTargetFramework` injects `TargetFramework` as a **global property** on the referenced project's build. - -```xml - - -``` - -Injecting the TFM the project already targets is **path-neutral** — the project already resolves to `bin\\net8.0\` and `obj\\net8.0\` on its own. So it doesn't change the output path; it only forks a distinct instance `(project, {TargetFramework=net8.0})`. The solution/graph builds the very same project as `(project, {})`. Both share the same `OutputPath`/`IntermediateOutputPath`, so the project is **built twice** to the same location — a bin/obj clash under parallel builds. - -**How to detect:** Follow the Primary workflow above. The `evaluations` and `evaluation_global_properties` tools surface two evaluations of the referenced project that share the same `OutputPath`/`IntermediateOutputPath` and differ only by a `TargetFramework` global property, while the project itself is single-targeting (its own `TargetFramework` already equals the injected value). The `double_writes` tool flags the resulting shared-file writes directly. - -**Note:** The P2P protocol itself does **not** inject `TargetFramework` for a non-multi-targeting reference — the clash comes specifically from the explicit `SetTargetFramework` metadata overriding that safe default. - -**Fix:** Remove the redundant `SetTargetFramework` when it just restates the project's own single TFM: - -```xml - - -``` - -**When `SetTargetFramework` is legitimate (not a clash):** - -- **Multi-targeting reference** — the referenced project uses `` and you need one specific TFM. Each TFM has a distinct output path, so no clash. -- **Overriding to a *different* TFM** — you may use `SetTargetFramework` on a single-targeting project to build it under a TFM *other than* the one it declares. Because the injected TFM then changes the output path (`obj\\\`), the instance no longer collides with `(project, {})`. Only the *same-TFM* case is path-neutral and clashing. -- **Framework-incompatible reference** — whenever the referencing and referenced projects target **incompatible frameworks** (e.g. a `.NETFramework` project referencing a `.NETCoreApp` project, or vice-versa) — **regardless of single- or multi-targeting on either side** — set `SkipGetTargetFrameworkProperties="true"` (the P2P `GetTargetFrameworkProperties` negotiation would otherwise fail) and `ReferenceOutputAssembly="false"` (an assembly built for an incompatible framework can't be consumed as a reference — you only want to trigger/sequence the build): - - ```xml - - ``` - - With `SkipGetTargetFrameworkProperties="true"`, the negotiation no longer stops the **referencing** project's own `TargetFramework` global property (present when it builds for a specific TFM, e.g. it is multi-targeting) from flowing into the referenced project. For a **single-targeting** referenced project that would force it to build under the wrong TFM / output path. Prevent it by either setting `SetTargetFramework="TargetFramework="` (pin the TFM) **or** `UndefineProperties="TargetFramework"` (strip the inherited global property so the project builds as it declares) — use one, not both: - - ```xml - - ``` - -See the `msbuild-antipatterns` skill (AP-23) for the authoring-time smell and rationale. - -## Tips - -- The SDK default paths include `$(TargetFramework)` — clashes often occur when projects override these defaults; normalize relative paths to absolute before comparing. -- **Cross-project `IntermediateOutputPath` clashes cannot be fixed with `AppendTargetFrameworkToOutputPath`** — files like `project.assets.json` are written directly to the intermediate path. For multi-targeting clashes *within the same project*, `AppendTargetFrameworkToOutputPath=true` is the correct fix. -- Error messages that indicate a path clash: `Cannot create a file when that file already exists` (NuGet restore), `The process cannot access the file because it is being used by another process`, or intermittent failures that succeed on retry. - -### Global Properties to Check When Comparing Evaluations - -When multiple evaluations share an output path, compare these global properties to understand why: - -| Property | Affects OutputPath? | Notes | -|----------|---------------------|-------| -| `TargetFramework` | Yes | Different TFMs should have different paths. **Exception:** re-injecting a *single-targeting* project's own TFM (e.g. via `SetTargetFramework` with the same value) is path-neutral — it forks a redundant instance sharing the output path (see "`SetTargetFramework` re-injecting...") | -| `RuntimeIdentifier` | Yes | Different RIDs should have different paths | -| `Configuration` | Yes | Debug vs Release | -| `Platform` | Yes | AnyCPU vs x64 etc. | -| `SolutionFileName` | No | Identifies which solution built the project — different values indicate multi-solution clash | -| `SolutionName` | No | Solution name without extension | -| `SolutionPath` | No | Full path to the solution file | -| `SolutionDir` | No | Directory containing the solution file | -| `CurrentSolutionConfigurationContents` | No | XML with project entries — count of entries reveals which solution | -| `BuildProjectReferences` | No | `false` = P2P query, not a real build - ignore these | -| `MSBuildRestoreSessionId` | No | Present = restore phase evaluation | -| `PublishReadyToRun` | No | Publish setting, doesn't change build output path but creates distinct project instances | -| `_IsPublishing` | No | Publish flag; an `` Build/Publish call with this set (in this project or another that consumes it) forks a publish instance sharing the build output path (see "Explicit `` Build/Publish with extra global properties") | - -## Testing Fixes - -After making changes to fix path clashes, clean and rebuild to verify. See the `binlog-generation` skill's "Cleaning the Repository" section on how to clean the repository while preserving binlog files. diff --git a/plugins/dotnet-msbuild/skills/eval-performance/SKILL.md b/plugins/dotnet-msbuild/skills/eval-performance/SKILL.md deleted file mode 100644 index 562168369b..0000000000 --- a/plugins/dotnet-msbuild/skills/eval-performance/SKILL.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -name: eval-performance -description: "Guide for diagnosing and improving MSBuild project evaluation performance. USE FOR: builds slow before any compilation starts, high evaluation time in binlog analysis, expensive glob patterns walking large directories (node_modules, .git, bin/obj), deep import chains (>20 levels), preprocessed output >10K lines indicating heavy evaluation, property functions with file I/O ($([System.IO.File]::ReadAllText(...))), multiple evaluations per project. Covers the 5 MSBuild evaluation phases, glob optimization via DefaultItemExcludes, import chain analysis with /pp preprocessing. DO NOT USE FOR: compilation-time slowness (use build-perf-diagnostics), incremental build issues (use incremental-build), non-MSBuild build systems." -license: MIT ---- - -# Diagnosing MSBuild Evaluation Performance - -Evaluation is the work MSBuild does *before* any target runs — reading project -files, processing imports, expanding globs. This skill helps you **find and -confirm** evaluation bottlenecks. Measure first; recommend a change only when a -measurement proves it is warranted. - -## Confirm the problem before changing anything - -Engage only when evaluation is *measurably* the bottleneck. Do NOT act when: - -- **The slowness is during compilation or target execution, not evaluation.** - That is not an evaluation problem — use `build-perf-diagnostics` instead. -- **The complaint is "rebuilds too much" / incremental build.** Use - `incremental-build` instead. -- **You have no measurement.** If no binlog or timing summary shows evaluation - is slow, gather one first (see below). Do not guess from reading project files. -- **A pattern below appears but evaluation is already fast.** Broad globs, deep - imports, or `EnableDefaultItems` are only worth flagging when the numbers show - they cost real time. A project that evaluates quickly needs no change. - -When a pattern is present but unmeasured, **report it as an observation and let -the user decide** — do not rewrite working configuration to match a "best -practice" without evidence it costs measurable evaluation time. Prefer the -smallest, most targeted change; never disable SDK defaults as a first move. - -## MSBuild Evaluation Phases - -For a comprehensive overview of MSBuild's evaluation and execution model, see [Build process overview](https://learn.microsoft.com/en-us/visualstudio/msbuild/build-process-overview). - -1. **Initial properties**: environment variables, global properties, reserved properties -2. **Imports and property evaluation**: process ``, evaluate `` top-to-bottom -3. **Item definition evaluation**: `` metadata defaults -4. **Item evaluation**: `` with `Include`, `Remove`, `Update`, glob expansion -5. **UsingTask evaluation**: register custom tasks - -Key insight: evaluation happens BEFORE any targets run. Slow evaluation = slow build start even when nothing needs compiling. - -## Diagnosing Evaluation Performance - -### Primary: binlog MCP (preferred) - -Use the **binlog MCP server** (`Microsoft.AITools.BinlogMcp`, exposed under the `binlog` MCP namespace) to analyze evaluation performance: - -1. Use the evaluations tool to list all evaluations and their durations -2. Use evaluation_global_properties to check for multiple evaluations with differing global properties -3. Use evaluation_properties to inspect evaluated properties for a specific project+TFM -4. Use imports tool to analyze the import chain depth and structure -5. Use properties tool to check for expensive property function evaluations - -### Fallback: text-log replay and preprocessing (when MCP is unavailable) - -### Using binlog - -1. Replay the binlog: `dotnet msbuild build.binlog -noconlog -fl -flp:v=diag;logfile=full.log` -2. Search for evaluation events: `grep -i 'Evaluation started\|Evaluation finished' full.log` -3. Multiple evaluations for the same project = overbuilding -4. Look for "Project evaluation started/finished" messages and their timestamps - -### Using /pp (preprocess) - -- `dotnet msbuild -pp:full.xml MyProject.csproj` -- Shows the fully expanded project with ALL imports inlined -- Use to understand: what's imported, import depth, total content volume -- Large preprocessed output (>10K lines) = heavy evaluation - -### Using /clp:PerformanceSummary - -- Add to build command for timing breakdown -- Shows evaluation time separately from target/task execution - -## Expensive Glob Patterns - -Only pursue these remedies once a measurement shows item evaluation is slow and -the globs are the cause; a custom glob that isn't walking large trees is fine. - -- Globs like `**/*.cs` walk the entire directory tree -- Default SDK globs are optimized, but custom globs may not be -- Problem: globbing over `node_modules/`, `.git/`, `bin/`, `obj/` — millions of files -- Remedy: use `` to exclude large directories -- Remedy: be specific with glob paths: `src/**/*.cs` instead of `**/*.cs` -- Remedy: use `false` only as a last resort (loses SDK defaults) — prefer the two options above first -- Check: grep for Compile items in the diagnostic log → if Compile items include unexpected files, globs are too broad - -## Import Chain Analysis - -- Deep import chains (>20 levels) slow evaluation -- Each import: file I/O + parse + evaluate -- Common causes: NuGet packages adding .props/.targets, framework SDK imports, Directory.Build chains -- Diagnosis: `/pp` output → search for ` - - - - - - - - - - - - -``` - -**Built-in task alternatives:** - -| Shell Command | MSBuild Task | -|--------------|--------------| -| `mkdir` | `` | -| `copy` / `cp` | `` | -| `del` / `rm` | `` | -| `move` / `mv` | `` | -| `echo text > file` | `` | -| `touch` | `` | -| `xcopy /s` | `` with item globs | - ---- - -## AP-02: Unquoted Condition Expressions - -**Smell**: `Condition="$(Foo) == Bar"` — either side of a comparison is unquoted. - -**Why it's bad**: If the property is empty or contains spaces/special characters, the condition evaluates incorrectly or throws a parse error. MSBuild requires single-quoted strings for reliable comparisons. - -```xml - - - true - - - - - true - -``` - -**Rule**: Always quote **both** sides of `==` and `!=` comparisons with single quotes. - ---- - -## AP-03: Hardcoded Absolute Paths - -**Smell**: Paths like `C:\tools\`, `D:\packages\`, `/usr/local/bin/` in project files. - -**Why it's bad**: Breaks on other machines, CI environments, and other operating systems. Not relocatable. - -```xml - - - C:\tools\mytool\mytool.exe - - - - - - $(MSBuildThisFileDirectory)tools\mytool\mytool.exe - - -``` - -**Preferred path properties:** - -| Property | Meaning | -|----------|---------| -| `$(MSBuildThisFileDirectory)` | Directory of the current .props/.targets file | -| `$(MSBuildProjectDirectory)` | Directory of the .csproj | -| `$([MSBuild]::GetDirectoryNameOfFileAbove(...))` | Walk up to find a marker file | -| `$([MSBuild]::NormalizePath(...))` | Combine and normalize path segments | - ---- - -## AP-04: Restating SDK Defaults - -**Smell**: Properties set to values that the .NET SDK already provides by default. - -**Why it's bad**: Adds noise, hides intentional overrides, and makes it harder to identify what's actually customized. When defaults change in newer SDKs, the redundant properties may silently pin old behavior. - -```xml - - - Library - true - true - MyLib - MyLib - true - - - - - net8.0 - -``` - ---- - -## AP-05: Manual File Listing in SDK-Style Projects - -**Smell**: ``, `` in SDK-style projects. - -**Why it's bad**: SDK-style projects automatically glob `**/*.cs` (and other file types). Explicit listing is redundant, creates merge conflicts, and new files may be accidentally missed if not added to the list. - -```xml - - - - - - - - - - - -``` - -**Exception**: Non-SDK-style (legacy) projects require explicit file includes. If migrating, see `msbuild-modernization` skill. - -**Exception (F# / `.fsproj`)**: F# compilation is order-dependent — the compiler processes `` items sequentially and a file can only reference types/modules declared in files listed above it. `.fsproj` files must therefore list every source file explicitly, in dependency order (utility/leaf modules at the top, the entry point such as `Program.fs` at the bottom). If a `.fsi` signature file is used, it must appear **immediately before** its companion `.fs` implementation file. - ---- - -## AP-06: Using `` with HintPath for NuGet Packages - -**Smell**: `` - -**Why it's bad**: This is the legacy `packages.config` pattern. It doesn't support transitive dependencies, version conflict resolution, or automatic restore. The `packages/` folder must be committed or restored separately. - -```xml - - - - ..\packages\Newtonsoft.Json.13.0.3\lib\netstandard2.0\Newtonsoft.Json.dll - - - - - - - -``` - -**Note**: `` without HintPath is still valid for .NET Framework GAC assemblies like `WindowsBase`, `PresentationCore`, etc. - ---- - -## AP-07: Missing `PrivateAssets="all"` on Analyzer/Tool Packages - -**Smell**: `` without `PrivateAssets="all"`. - -**Why it's bad**: Without `PrivateAssets="all"`, analyzer and build-tool packages flow as transitive dependencies to consumers of your library. Consumers get unwanted analyzers or build-time tools they didn't ask for. - -See [`references/private-assets.md`](references/private-assets.md) for BAD/GOOD examples and the full list of packages that need this. - ---- - -## AP-08: Copy-Pasted Properties Across Multiple .csproj Files - -**Smell**: The same `` block appears in 3+ project files. - -**Why it's bad**: Maintenance burden — a change must be made in every file. Inconsistencies creep in over time. - -```xml - - - - enable - true - enable - - - - - - - enable - true - enable - - -``` - -See `directory-build-organization` skill for full guidance on structuring `Directory.Build.props` / `Directory.Build.targets`. - ---- - -## AP-09: Scattered Package Versions Without Central Package Management - -**Smell**: `` with different versions of the same package across projects. - -**Why it's bad**: Version drift — different projects use different versions of the same package, leading to runtime mismatches, unexpected behavior, or diamond dependency conflicts. - -```xml - - - - - -``` - -**Fix:** Use Central Package Management. See [https://learn.microsoft.com/en-us/nuget/consume-packages/central-package-management](https://learn.microsoft.com/en-us/nuget/consume-packages/central-package-management) for details. - ---- - -## AP-10: Monolithic Targets (Too Much in One Target) - -**Smell**: A single `` with 50+ lines doing multiple unrelated things. - -**Why it's bad**: Can't skip individual steps via incremental build, hard to debug, hard to extend, and the target name becomes meaningless. - -```xml - - - - - - - - - - - - - - - - - - - - - - -``` - ---- - -## AP-11: Custom Targets Missing `Inputs` and `Outputs` - -**Smell**: `` with no `Inputs` / `Outputs` attributes. - -**Why it's bad**: The target runs on every build, even when nothing changed. This defeats incremental build and slows down no-op builds. - -See [`references/incremental-build-inputs-outputs.md`](references/incremental-build-inputs-outputs.md) for BAD/GOOD examples and the full pattern including FileWrites registration. - -See `incremental-build` skill for deep guidance on Inputs/Outputs, FileWrites, and up-to-date checks. - ---- - -## AP-12: Setting Defaults in .targets Instead of .props - -**Smell**: `` with default values inside a `.targets` file. - -**Why it's bad**: `.targets` files are imported late (after project files). By the time they set defaults, other `.targets` files may have already used the empty/undefined value. `.props` files are imported early and are the correct place for defaults. - -```xml - - - 2.0 - - - - - - - - - 2.0 - - - - - - -``` - -**Rule**: `.props` = defaults and settings (evaluated early). `.targets` = build logic and targets (evaluated late). - ---- - -## AP-13: Import Without `Exists()` Guard - -**Smell**: `` without a `Condition="Exists('...')"` check. - -**Why it's bad**: If the file doesn't exist (not yet created, wrong path, deleted), the build fails with a confusing error. Optional imports should always be guarded. - -```xml - - - - - - - - -``` - -**Exception — required imports**: Imports that are *required* for the build to work correctly should fail fast — don't guard those. Guard imports that are optional or environment-specific (e.g., local developer overrides, CI-specific settings). - -**Exception — NuGet package forwarders**: `.props`/`.targets` files inside a NuGet package's per-TFM `build/` or `buildTransitive/` folder routinely import a sibling file under `buildTransitive//…` without an `Exists()` guard. These are a **package contract**: the target file is guaranteed to be present in the restored package, even if it doesn't appear in the source tree at that relative path. The package layout is typically produced by: - -- A custom `.nuspec` with per-TFM `` entries — e.g. `` — that copy files from a single source folder (such as `buildTransitive/common/`) into per-TFM subfolders at pack time, or -- `` / `` items in the `.csproj` with a per-TFM `` (e.g. `buildTransitive/net8.0/`), declared once per target TFM, or -- SDK conventions (e.g. `IncludeBuildOutput`, `BuildOutputTargetFolder`) that place built outputs under `build//`. - -Before flagging an unguarded `` inside a `build/` or `buildTransitive/` folder, **resolve it against the packed layout** — read every `*.nuspec` in the project directory **and its immediate parent directory** (shared nuspecs are common in mono-repos; do not walk further up), and any `` metadata on ``/`` items in the `.csproj`. Only flag if the target path is missing from **both** the source tree *and* the projected package layout. The `dotnet-msbuild/extension-points` skill — *Source tree vs packed layout* — documents the full cross-check procedure. - -**Forwarding `buildTransitive/` → `build/`:** forward through the sibling `build/*.props` / `build/*.targets` file (not directly to `buildMultiTargeting/`); when `build/` is per-TFM (`build//`), include the TFM segment derived from the file's own folder (not `$(TargetFramework)`), or transitive consumers hit `MSB4019`. See the `extension-points` skill — *Forwarding chain* — for the rule and derivation expression. - ---- - -## AP-14: Backslashes in Paths — Where It Matters - -**Smell**: Backslash path separators in `.props`/`.targets` files meant to run cross-platform. - -**Where this is a real bug (🔴 Error)** — paths that MSBuild does **not** route through its path normalizer: - -- Raw shell strings inside `` — passed verbatim to `bash`/`sh` on Unix, which treats `\` as an escape. -- Backslash-delimited paths inside CDATA blocks, embedded in source files written by ``, or constructed for non-MSBuild consumers (custom scripts, response files, environment variables). -- Paths handed to custom tasks that call OS file APIs directly without going through MSBuild path utilities. - -**Where this is only a style preference (🔵 Style)** — paths that go through MSBuild's evaluator (``, file-path properties consumed by built-in tasks like ``/``/``, item `Include=`/`Exclude=` globs): - -MSBuild's evaluator normalizes `\` → `/` on Unix-like systems before resolving the path. See `FileUtilities.MaybeAdjustFilePath` and `ConvertToUnixSlashes` in [`microsoft/msbuild` `src/Framework/FileUtilities.cs`](https://github.com/dotnet/msbuild/blob/main/src/Framework/FileUtilities.cs). So `` resolves correctly on Linux/macOS today. Forward slashes are still **preferred for consistency**, but the import will not break and existing backslash-style imports should not be flagged as 🔴 **Error**. - -```xml - - - - - - - - -``` - -**Verification rule**: Before flagging a backslash path as 🔴 **Error**, ask *"does this string flow through MSBuild's evaluator, or is it handed verbatim to a non-MSBuild consumer?"* Only the second case is a correctness defect. - -**Note**: `$(MSBuildThisFileDirectory)` already ends with a platform-appropriate separator, so `$(MSBuildThisFileDirectory)tools/mytool` works on both platforms. - ---- - -## AP-15: Unconditional Property Override in Multiple Scopes - -**Smell**: A property set unconditionally in both `Directory.Build.props` and a `.csproj` — last write wins silently. - -**Why it's bad**: Hard to trace which value is actually used. Makes the build fragile and confusing for anyone reading the project files. - -```xml - - - - bin\custom\ - - - - bin\other\ - - - - - - bin\custom\ - - -``` - ---- - -For additional anti-patterns (AP-16 through AP-23) and a quick-reference checklist, see [additional-antipatterns.md](references/additional-antipatterns.md). diff --git a/plugins/dotnet-msbuild/skills/msbuild-antipatterns/references/additional-antipatterns.md b/plugins/dotnet-msbuild/skills/msbuild-antipatterns/references/additional-antipatterns.md deleted file mode 100644 index 9ad2e8e9f0..0000000000 --- a/plugins/dotnet-msbuild/skills/msbuild-antipatterns/references/additional-antipatterns.md +++ /dev/null @@ -1,315 +0,0 @@ -## AP-16: Using `` for String/Path Operations - -**Smell**: `` or `` for simple string manipulation. - -**Why it's bad**: Shell-dependent, not cross-platform, slower than property functions, and the result is hard to capture back into MSBuild properties. - -```xml - - - - - - - - $(Version.Replace('-preview', '')) - $(Version.Contains('-')) - $(AssemblyName.ToLowerInvariant()) - - - - - $([MSBuild]::NormalizeDirectory($(OutputPath))) - $([System.IO.Path]::Combine($(MSBuildThisFileDirectory), 'tools', 'mytool.exe')) - -``` - ---- - -## AP-17: Mixing `Include` and `Update` for the Same Item Type in One ItemGroup - -**Smell**: Same `` has both `` and ``. - -**Why it's bad**: `Update` acts on items already in the set. If `Include` hasn't been processed yet (evaluation order), `Update` may not find the item. Separating them avoids subtle ordering bugs. - -```xml - - - - - - - - - - - - - -``` - ---- - -## AP-18: Redundant `` to Transitively-Referenced Projects - -**Smell**: A project references both `Core` and `Utils`, but `Core` already depends on `Utils`. - -**Why it's bad**: Adds unnecessary coupling, makes the dependency graph harder to understand, and can cause ordering issues in large builds. MSBuild resolves transitive references automatically. - -```xml - - - - - - - - - - -``` - -**Caveat**: If you need to use types from `Utils` directly (not just transitively), the explicit reference is appropriate. But verify whether the direct dependency is actually needed. - ---- - -## AP-19: Side Effects During Property Evaluation - -**Smell**: Property functions that write files, make network calls, or modify state during `` evaluation. - -**Why it's bad**: Property evaluation happens during the evaluation phase, which can run multiple times (e.g., during design-time builds in Visual Studio). Side effects are unpredictable and can corrupt state. - -```xml - - - $([System.IO.File]::WriteAllText('stamp.txt', 'built')) - - - - - - -``` - ---- - -## AP-20: Platform-Specific Exec Without OS Condition - -**Smell**: `` or `` without an OS condition. - -**Why it's bad**: Fails on the wrong platform. If the project is cross-platform, guard platform-specific commands. - -```xml - - - - - - - - - -``` - ---- - -## AP-21: Property Conditioned on TargetFramework in .props Files - -**Smell**: `` or `` in `Directory.Build.props` or any `.props` file imported before the project body. - -**Why it's bad**: `$(TargetFramework)` is NOT reliably available in `Directory.Build.props` or any `.props` file imported before the project body. It is only set that early for multi-targeting projects, which receive `TargetFramework` as a global property from the outer build. Single-targeting projects (using singular ``) set it in the project body, which is evaluated *after* `.props`. This means property conditions on `$(TargetFramework)` in `.props` files silently fail for single-targeting projects — the condition never matches because the property is empty. This applies to both `` and individual `` elements. - -For a detailed explanation of MSBuild's evaluation and execution phases, see [Build process overview](https://learn.microsoft.com/en-us/visualstudio/msbuild/build-process-overview). - -```xml - - - $(DefineConstants);MY_FEATURE - - - - - $(DefineConstants);MY_FEATURE - - - - - $(DefineConstants);MY_FEATURE - - - - - - $(DefineConstants);MY_FEATURE - -``` - -**⚠️ Item and Target conditions are NOT affected.** This restriction applies ONLY to property conditions (`` and ``). Item conditions (``) and Target conditions in `.props` files are SAFE because items and targets evaluate after all properties (including those set in the project body) have been evaluated. This includes `PackageVersion` items in `Directory.Packages.props`, `PackageReference` items in `Directory.Build.props`, and any other item types. - -**Do NOT flag the following patterns — they are correct:** - -```xml - - - - - - - - - - - - - - - - - -``` - ---- - -## AP-22: Forking a Project Instance via `` with Path-Neutral Global Properties - -**Smell**: A target uses the `` task to build or publish a project, passing extra `Properties` that don't change that project's output path. Two common shapes: - -```xml - - - - - -``` - -**Why it's bad**: An MSBuild project instance is identified by its path **plus its global properties**. Passing an extra global property creates a *distinct* instance of the target project — `(project, {_IsPublishing=true})` — that still resolves to the same `OutputPath`/`IntermediateOutputPath` as the instance the solution/graph already builds, `(project, {})`. That project is then built twice, and in a parallel/graph build the two instances can write the same files concurrently (PDBs, `*.sourcelink` and other NativeAOT intermediates, `project.assets.json`), producing `The process cannot access the file because it is being used by another process` or intermittent file-lock failures. This applies whether the offending `` call is in the target project itself or in some other project in the same build. Use the `check-bin-obj-clash` skill to confirm two evaluations of that project differ only by a path-neutral property while sharing an output path. - -```xml - - - - -``` - -```xml - - - - <_PublishWasInvokedDirectly Condition="'$(_IsPublishing)' == 'true'">true - <_IsPublishing>true - - - -``` - -For (a), the static property keeps everything in one instance (one output path, nothing to race); running `Publish` via `DependsOnTargets` (or `CallTarget`) reuses that instance instead of forking. The `_PublishWasInvokedDirectly` guard breaks the target cycle when publish is the entry point (e.g. `dotnet publish`, which sets `_IsPublishing=true` as a global property and would otherwise re-trigger `PublishOnBuild`). - -```xml - - - - - - - - -``` - -For (b), the consumer must not fork the producer with path-neutral global properties. Let the producer publish itself (one instance), reference it only to sequence the build, and read its output. - -**When extra global properties ARE fine**: only when the output path encodes the discriminator (`RuntimeIdentifier`, `TargetFramework`, `Configuration`, `Platform`) so each instance writes to a distinct directory. If you must invoke a project with a path-neutral property, give that build its own `BaseIntermediateOutputPath`/output path so it can't collide. - ---- - -## AP-23: `SetTargetFramework` Metadata on a `ProjectReference` to a Non-Multi-Targeting Project - -**Smell**: A `` carries `SetTargetFramework="TargetFramework=net8.0"` (or similar) metadata, the referenced project is **single-targeting** (uses singular ``, not ``), **and the injected TFM equals the TFM the project already targets**. - -```xml - - - - -``` - -**Why it's bad**: `SetTargetFramework` injects `TargetFramework` as a **global property** on the referenced project's build. That mechanism exists so a consumer can pick *one specific TFM* of a **multi-targeting** project — different TFM values produce different output paths, so each build is distinct and safe. - -For a **single-targeting** project, injecting the TFM it **already targets** is **path-neutral**: the project already resolves to `bin\\net8.0\` and `obj\\net8.0\` on its own, so the extra global property doesn't change the output path — it only creates a *distinct* MSBuild project instance `(project, {TargetFramework=net8.0})`. Meanwhile the solution/graph builds that same project as `(project, {})` with no global properties. Both instances resolve to the **same** `OutputPath`/`IntermediateOutputPath`, so the project is **built twice** and the two instances write the same files (assemblies, PDBs, `project.assets.json`, etc.). Under a parallel build this is a classic bin/obj clash — `The process cannot access the file because it is being used by another process` or intermittent, retry-flaky failures. (Injecting a *different* TFM changes the output path and is a legitimate override — see below.) - -Note the healthy contrast: the P2P protocol itself does **not** inject `TargetFramework` when it sees a non-multi-targeting reference — it correctly omits the global property. `SetTargetFramework` overrides that safe default and is what reintroduces the clash. Use the `check-bin-obj-clash` skill to confirm two evaluations of the referenced project differ only by a path-neutral `TargetFramework` global property while sharing an output path. - -```xml - - - - -``` - -**When `SetTargetFramework` IS appropriate**: - -1. **Multi-targeting reference** — the referenced project is multi-targeting (``) and you deliberately need to consume a specific TFM. Each TFM has its own output path, so the forked instance doesn't collide. - -2. **Deliberately overriding a single-targeting project's TFM to a *different* value** — you can use `SetTargetFramework` on a single-targeting reference to build it under a TFM *other than* the one it declares. This is only valid when the passed-in TFM **differs** from what the project single-targets: because the injected `TargetFramework` then changes the output path (`obj\\\`), the instance no longer collides with the `(project, {})` build. It is **only** the redundant case — passing the *same* TFM the project already targets (path-neutral) — that causes the clash. - -**Related: referencing a framework-incompatible project.** Independently of the clash above, whenever the referencing and referenced projects target **incompatible frameworks** (e.g. a `.NETFramework` project referencing a `.NETCoreApp` project, or vice-versa) — **regardless of whether either side is single- or multi-targeting** — you must set both: -- `SkipGetTargetFrameworkProperties="true"` — bypass the P2P `GetTargetFrameworkProperties` negotiation, which would otherwise fail because the frameworks aren't compatible, and -- `ReferenceOutputAssembly="false"` — because an assembly built for an incompatible framework can't be consumed as a reference; you only want to trigger/sequence the build, not reference its output. - -```xml - - -``` - -**⚠️ Prevent the referencing project's `TargetFramework` from leaking.** When `SkipGetTargetFrameworkProperties="true"` bypasses the negotiation, nothing stops the referencing project's own `TargetFramework` **global property** (present whenever the referencing project is being built for a specific TFM — e.g. it is multi-targeting) from flowing down into the referenced project. If it flows into a **single-targeting** referenced project, that project builds under the *wrong* TFM (and to a different, wrong output path). Guard against it one of two ways: -- set `SetTargetFramework="TargetFramework="` to explicitly pin the referenced build's TFM (also required for multi-targeting references), **or** -- for a single-targeting referenced project you want to build as-declared, set `UndefineProperties="TargetFramework"` to strip the inherited global property so the project uses its own ``. - -```xml - - -``` - -Add `SetTargetFramework` on top of these **only** if you also need to pin the referenced build to a specific TFM (a multi-targeting project, or a single-targeting project you're overriding to a *different* TFM per case 2 above). Use `SetTargetFramework` **or** `UndefineProperties="TargetFramework"`, not both — the former sets the property, the latter removes it. - ---- - -## Quick-Reference Checklist - -When reviewing an MSBuild file, scan for these in order: - -| # | Check | Severity | -|---|-------|----------| -| AP-02 | Unquoted conditions | 🔴 Error-prone | -| AP-19 | Side effects in evaluation | 🔴 Dangerous | -| AP-21 | Property conditioned on TargetFramework in .props | 🔴 Silent failure | -| AP-22 | Forking a project instance via `` with path-neutral global properties (self or cross-project) | 🔴 Race/duplicate build | -| AP-23 | `SetTargetFramework` re-injecting a single-targeting project's own TFM on a `ProjectReference` | 🔴 Race/duplicate build | -| AP-03 | Hardcoded absolute paths | 🔴 Broken on other machines | -| AP-06 | `` with HintPath for NuGet | 🟡 Legacy | -| AP-07 | Missing `PrivateAssets="all"` on tools | 🟡 Leaks to consumers | -| AP-11 | Missing Inputs/Outputs on targets | 🟡 Perf regression | -| AP-13 | Import without Exists guard | 🟡 Fragile | -| AP-05 | Manual file listing in SDK-style | 🔵 Noise | -| AP-04 | Restating SDK defaults | 🔵 Noise | -| AP-08 | Copy-paste across csproj files | 🔵 Maintainability | -| AP-09 | Scattered package versions | 🔵 Version drift | -| AP-01 | `` for built-in tasks | 🔵 Cross-platform | -| AP-14 | Backslashes in cross-platform paths | 🔵 Cross-platform | -| AP-10 | Monolithic targets | 🔵 Maintainability | -| AP-12 | Defaults in .targets instead of .props | 🔵 Ordering issue | -| AP-15 | Unconditional property override | 🔵 Confusing | -| AP-16 | `` for string operations | 🔵 Preference | -| AP-17 | Mixed Include/Update in one ItemGroup | 🔵 Subtle bugs | -| AP-18 | Redundant transitive ProjectReferences | 🔵 Graph noise | -| AP-20 | Platform-specific Exec without guard | 🔵 Cross-platform | diff --git a/plugins/dotnet-msbuild/skills/msbuild-antipatterns/references/incremental-build-inputs-outputs.md b/plugins/dotnet-msbuild/skills/msbuild-antipatterns/references/incremental-build-inputs-outputs.md deleted file mode 100644 index 7c54447b26..0000000000 --- a/plugins/dotnet-msbuild/skills/msbuild-antipatterns/references/incremental-build-inputs-outputs.md +++ /dev/null @@ -1,30 +0,0 @@ -# Incremental Build: Inputs and Outputs on Custom Targets - -Custom targets **must** specify `Inputs` and `Outputs` attributes so MSBuild can skip them when up-to-date. Without both attributes, the target runs on every build. - -```xml - - - - - - - - - - - - - -``` - -**Key points:** -- **`Inputs`** should include `$(MSBuildProjectFile)` plus any source files that drive generation -- **`Outputs`** should use `$(IntermediateOutputPath)` so generated files go in `obj/` and are managed by MSBuild -- **`FileWrites`** registration ensures `dotnet clean` removes the generated file -- **`Compile` inclusion** adds the generated file to compilation without requiring it at evaluation time - -See the `incremental-build` skill for deep guidance on diagnosing broken incremental builds, FileWrites tracking, and Visual Studio's Fast Up-to-Date Check. diff --git a/plugins/dotnet-msbuild/skills/msbuild-antipatterns/references/private-assets.md b/plugins/dotnet-msbuild/skills/msbuild-antipatterns/references/private-assets.md deleted file mode 100644 index e9414eb5cb..0000000000 --- a/plugins/dotnet-msbuild/skills/msbuild-antipatterns/references/private-assets.md +++ /dev/null @@ -1,22 +0,0 @@ -# PrivateAssets for Analyzers and Build Tools - -Analyzer and build-tool packages should always use `PrivateAssets="all"` to prevent them from flowing as transitive dependencies to consumers of your library. - -```xml - - - - - - - - - -``` - -**Packages that almost always need `PrivateAssets="all"`:** -- Roslyn analyzers (`*.Analyzers`, `*.CodeFixes`) -- Source generators -- SourceLink packages (`Microsoft.SourceLink.*`) -- Versioning tools (`MinVer`, `Nerdbank.GitVersioning`) -- Build-only tools (`Microsoft.DotNet.ApiCompat`, etc.) diff --git a/plugins/dotnet-test/skills/migrate-static-to-wrapper/SKILL.md b/plugins/dotnet-test/skills/migrate-static-to-wrapper/SKILL.md deleted file mode 100644 index e91d47583b..0000000000 --- a/plugins/dotnet-test/skills/migrate-static-to-wrapper/SKILL.md +++ /dev/null @@ -1,237 +0,0 @@ ---- -name: migrate-static-to-wrapper -description: > - Replace existing static dependency call sites with a wrapper or built-in - abstraction that already exists or is registered in DI, across a bounded scope - (file, project, namespace). - USE FOR: replace DateTime.UtcNow/DateTime.Now with TimeProvider and add the - constructor parameter, migrate static call sites to a wrapper already in DI, - bulk replace File.* with IFileSystem, scoped migration of statics in only - certain files, update unit tests to a fake time source, make an existing - static or utility class testable by adding an ambient - TimeProvider/IFileSystem seam while every current call site keeps compiling, - behavior-preserving time refactors that must keep the same DateTimeKind. - DO NOT USE FOR: detecting statics (use detect-static-dependencies), designing a - brand-new wrapper interface that does not exist yet (use - generate-testability-wrappers), migrating between test frameworks. -license: MIT ---- - -# Migrate Static to Wrapper - -Perform mechanical, codemod-style replacement of static dependency call sites with calls to injected wrapper interfaces or built-in abstractions. Operates on a bounded scope (single file, project, or namespace) so migrations can be done incrementally. - -## When to Use - -- After wrappers have been generated (via `generate-testability-wrappers`) or built-in abstractions identified -- Migrating `DateTime.UtcNow` → `TimeProvider.GetUtcNow()` across a project -- Migrating `File.*` → `IFileSystem.File.*` across a namespace -- Adding constructor injection for the new abstraction to affected classes -- Making a `static` utility class testable by adding an ambient seam (Step 3) while its existing call sites keep - compiling unchanged -- Incremental migration: one project or namespace at a time - -## When Not to Use - -- No wrapper or abstraction exists yet and one must be designed from scratch (use `generate-testability-wrappers` first). - A built-in abstraction such as `TimeProvider` or `IFileSystem` always counts as existing. -- The user wants to detect statics, not migrate them (use `detect-static-dependencies`) -- Migrating between test frameworks (use the appropriate migration skill) - -> A class that is `static`, or a project with no DI container, is **not** a reason to skip this skill — that is exactly -> what the ambient seam in Step 3 is for. Use it whenever the call sites must keep compiling unchanged. - -## Inputs - -| Input | Required | Description | -|-------|----------|-------------| -| Static pattern | Yes | What to replace (e.g., `DateTime.UtcNow`, `File.ReadAllText`) | -| Replacement abstraction | Yes | What to use instead (e.g., `TimeProvider`, `IFileSystem`) | -| Scope | Yes | File path, project (.csproj), namespace, or directory to migrate | -| Injection strategy | No | `constructor` (default), `primary-constructor`, or `ambient` | - -## Workflow - -### Step 1: Verify prerequisites - -Before modifying any code: - -1. **Confirm the wrapper/abstraction exists**: Check that the interface or built-in abstraction is available in the project. For `TimeProvider`, verify the target framework is .NET 8+ or `Microsoft.Bcl.TimeProvider` is referenced. For `System.IO.Abstractions`, verify the NuGet package is referenced. - -2. **Confirm DI registration exists**: Check `Program.cs` or `Startup.cs` for the service registration. If missing, add it before proceeding. - -3. **Identify all files in scope**: List the `.cs` files that will be modified. Exclude test projects, `obj/`, `bin/`, and generated code. - -### Step 2: Plan the migration for each file - -**Migrate exactly what was asked — nothing adjacent.** If the user named a member (`DateTime.UtcNow`), migrate only that member and leave siblings such as `DateTime.Now` untouched. If the user named files, do not touch other files. Never migrate a call site whose comment or name marks it as deliberate (e.g. `// intentional local time`). List everything you deliberately left alone under "Remaining (out of scope)" so the user can ask for it in a follow-up; suggesting is fine, silently widening the scope is not. - -For each file containing the static pattern, determine: - -1. **Which class(es) contain the call sites** — identify the class declarations -2. **Whether the class already has the dependency injected** — check constructors for existing `TimeProvider`, `IFileSystem`, etc. parameters -3. **The replacement expression** for each call site - -#### Replacement mapping - -| Category | Original | DI replacement | -|----------|----------|----------------| -| Time | `DateTime.Now` | `_timeProvider.GetLocalNow().LocalDateTime` | -| Time | `DateTime.UtcNow` | `_timeProvider.GetUtcNow().UtcDateTime` | -| Time | `DateTime.Today` | `_timeProvider.GetLocalNow().LocalDateTime.Date` | -| Time | `DateTimeOffset.Now` | `_timeProvider.GetLocalNow()` | -| Time | `DateTimeOffset.UtcNow` | `_timeProvider.GetUtcNow()` | -| File | `File.ReadAllText(path)` | `_fileSystem.File.ReadAllText(path)` | -| File | `File.WriteAllText(path, text)` | `_fileSystem.File.WriteAllText(path, text)` | -| File | `File.Exists(path)` | `_fileSystem.File.Exists(path)` | -| File | `Directory.Exists(path)` | `_fileSystem.Directory.Exists(path)` | -| Env | `Environment.GetEnvironmentVariable(name)` | `_env.GetEnvironmentVariable(name)` | -| Console | `Console.WriteLine(msg)` | `_console.WriteLine(msg)` | -| Process | `Process.Start(info)` | `_processRunner.Start(info)` | - -Apply the same pattern for other members in each category. - -> **Preserve `DateTimeKind` — this is the most common silent regression.** `TimeProvider.GetUtcNow()` / `GetLocalNow()` return a `DateTimeOffset`. Converting back to `DateTime` **must keep the original `Kind`**, otherwise you introduce a behavioral change even though the code still compiles: -> -> - `DateTime.UtcNow` has `Kind == Utc` → use `.UtcDateTime` (**not** `.DateTime`, which yields `Kind == Unspecified`). -> - `DateTime.Now` has `Kind == Local` → use `.LocalDateTime` (**not** `.DateTime`). -> - When a call site consumes a `DateTimeOffset` directly (a field/parameter/return already typed `DateTimeOffset`), drop the `.UtcDateTime`/`.LocalDateTime` suffix and assign the `DateTimeOffset` as-is — don't force it back through `DateTime`. -> -> Match the **target member's type**: if the surrounding field/property is `DateTime`, keep it `DateTime` (via the Kind-correct property above); do not change it to `DateTimeOffset` as part of a "mechanical" migration — that is a design change, not a delegation. - -### Step 3: Add constructor injection - -Add the new dependency following the class's existing pattern: - -- **Primary constructor** (C# 12+): Add parameter to primary constructor: `public class OrderProcessor(ILogger logger, TimeProvider timeProvider)` -- **Traditional constructor**: Add `private readonly` field + constructor parameter, matching the existing field naming convention (`_camelCase` or `m_camelCase`) - -#### Static classes: use ambient context (no constructor injection) - -A `static` class with only static members **cannot** receive constructor injection — adding an instance constructor or instance field would break it. Do **not** convert it to a non-static class just to inject the dependency; that changes its design and every call site. Instead, apply the **ambient context** pattern: expose a static, settable seam that defaults to the real implementation and is overridden once at composition/test setup. - -When the user wants to keep the class static, the ambient seam below **is the answer** — present it as *the* solution and implement it directly. Do **not** hedge by offering "convert it to a non-static class" or "pass `TimeProvider` as a method parameter" as co-equal alternatives; those change the class's design or public API and are not what was asked. Lead with the seam, then note the parallelism trade-off. - -```csharp -public static class TimestampFormatter -{ - // Ambient seam — defaults to the real clock, swap in tests. - public static TimeProvider Clock { get; set; } = TimeProvider.System; - - public static string Now() => Clock.GetUtcNow().ToString("O"); -} -``` - -- Production: leave `Clock` at its `TimeProvider.System` default, or assign the DI-resolved `TimeProvider` once at startup (`TimestampFormatter.Clock = app.Services.GetRequiredService();`). -- Tests: override `Clock` with a `FakeTimeProvider` and **always restore it in a `finally`** so a failing assertion can't leak the fake into other tests: - - ```csharp - var original = TimestampFormatter.Clock; - TimestampFormatter.Clock = new FakeTimeProvider(instant); - try - { - // exercise code under test - } - finally - { - TimestampFormatter.Clock = original; - } - ``` - -- **Parallelism caveat**: a mutable static seam is process-global. Tests that mutate it must **not** run in parallel with each other (or with code that reads it) — put them in a non-parallel collection/class (e.g. xUnit `[Collection]` with parallelization disabled, or MSTest `[DoNotParallelize]`). Only if the class is *not* required to stay static and its tests must run fully parallel should you consider converting the caller to an instance with constructor injection instead — otherwise keep the ambient seam. -- The same seam works for other statics (`IFileSystem`, custom wrappers): a `public static X { get; set; }` defaulting to the real implementation, with the same restore-in-`finally` and non-parallel discipline. - -### Step 4: Replace call sites - -Perform each replacement mechanically. For each call site: - -1. Replace the static call with the wrapper call -2. Preserve the surrounding code structure (whitespace, comments, chaining) -3. Add required `using` directives if not already present - -#### Adding using directives - -| Abstraction | Using directive | -|------------|-----------------| -| `TimeProvider` | None (in `System` namespace) | -| `IFileSystem` | `using System.IO.Abstractions;` | -| `IHttpClientFactory` | `using System.Net.Http;` (usually already present) | -| Custom wrappers | `using ;` | - -### Step 5: Update affected test files - -If test files exist for the migrated classes: - -1. **Update constructor calls** — add the new parameter to test class instantiation -2. **Use test doubles**: - - `TimeProvider` → `new FakeTimeProvider()` from `Microsoft.Extensions.TimeProvider.Testing` - - `IFileSystem` → `new MockFileSystem()` from `System.IO.Abstractions.TestingHelpers` - - Custom wrappers → `new Mock()` or hand-rolled fake - -### Step 6: Build verification - -After all changes in the current scope: - -```bash -dotnet build -``` - -**Report the build result you actually observed.** Only write "build succeeded" when the command exited 0; if it failed — including restore/NuGet failures such as "assets file not found" — say so, quote the error, and either fix it (`dotnet restore`, add the missing package) or hand the user a precise blocker. A false success claim is worse than an unfinished migration. - -If the build fails: -- **Missing using**: Add the required `using` directive -- **Missing NuGet package**: Run `dotnet add package ` -- **Constructor mismatch in tests**: Update test instantiation (Step 5) -- **Ambiguous call**: Fully qualify the wrapper call - -### Step 7: Report changes - -Summarize what was done: - -``` -## Migration Summary - -**Pattern**: DateTime.UtcNow → TimeProvider.GetUtcNow() -**Scope**: MyProject/Services/ - -### Files Modified (production) -| File | Call Sites Replaced | Injection Added | -|------|--------------------:|:----------------| -| OrderProcessor.cs | 3 | Yes (constructor) | -| NotificationService.cs | 1 | Yes (primary ctor) | - -### Files Modified (tests) -| File | Change | -|------|--------| -| OrderProcessorTests.cs | Added FakeTimeProvider parameter | - -### Remaining (out of scope) -- MyProject/Legacy/ — 8 call sites not migrated (different namespace) -``` - -## Validation - -- [ ] All call sites in scope were replaced (none missed) -- [ ] No call site outside the requested member/file scope was modified -- [ ] Call sites documented as intentional (e.g. local time) were left untouched and reported -- [ ] Constructor injection added to all affected classes -- [ ] Field naming follows existing class conventions -- [ ] Required `using` directives added -- [ ] Required NuGet packages referenced -- [ ] Build succeeds after migration, and the reported result matches the actual command exit code -- [ ] Test files updated with appropriate test doubles -- [ ] No behavioral changes introduced (wrapper delegates directly to the static) -- [ ] `DateTimeKind` preserved — former `DateTime.UtcNow` stays `Utc` (`.UtcDateTime`), former `DateTime.Now` stays `Local` (`.LocalDateTime`) - -## Common Pitfalls - -| Pitfall | Solution | -|---------|----------| -| Replacing statics in test code | Only replace in production code; tests should use fakes/mocks | -| Breaking static classes | Static classes can't have constructors — use the ambient context seam (Step 3) instead of converting them to non-static | -| Missing `FakeTimeProvider` NuGet | Add `Microsoft.Extensions.TimeProvider.Testing` to test project | -| Replacing a `DateTime` value with `.DateTime` off a `DateTimeOffset` | `DateTimeOffset.DateTime` returns `Kind == Unspecified` — use `.UtcDateTime` (for former `DateTime.UtcNow`) or `.LocalDateTime` (for former `DateTime.Now`) to preserve the original `DateTimeKind`. Only change the field/return type to `DateTimeOffset` if the user asked for it. | -| Migrating too much at once | Stick to the defined scope — one project or namespace per run | -| Migrating `DateTime.Now` when only `UtcNow` was requested | Respect the literal request; list the other call sites as out-of-scope suggestions instead of rewriting them | -| Claiming "Build succeeded" after a failed restore | Read the exit code and output; report the real failure and fix it or surface it as a blocker | -| Forgetting DI registration | Always verify `Program.cs`/`Startup.cs` has the registration before replacing call sites | diff --git a/plugins/dotnet-upgrade/skills/dotnet-aot-compat/SKILL.md b/plugins/dotnet-upgrade/skills/dotnet-aot-compat/SKILL.md deleted file mode 100644 index bcfeca1068..0000000000 --- a/plugins/dotnet-upgrade/skills/dotnet-aot-compat/SKILL.md +++ /dev/null @@ -1,269 +0,0 @@ ---- -name: dotnet-aot-compat -description: > - Make .NET projects compatible with Native AOT and trimming by systematically - resolving IL trim/AOT analyzer warnings. USE FOR: making projects AOT-compatible, - fixing trimming warnings, resolving IL warnings (IL2026, IL2070, IL2067, IL2072, - IL3050), adding DynamicallyAccessedMembers annotations, enabling IsAotCompatible. - DO NOT USE FOR: publishing native AOT binaries, optimizing binary size, replacing - reflection-heavy libraries with alternatives. - INVOKES: no tools — pure knowledge skill. -license: MIT ---- - -# dotnet-aot-compat - -Make .NET projects compatible with Native AOT and trimming by systematically resolving all IL trim/AOT analyzer warnings. - -## When to Use This Skill - -- **"Make this project AOT-compatible"** -- **"Fix trimming warnings"** or **"fix IL warnings"** -- **"Resolve IL2070 / IL2067 / IL2072 / IL2026 / IL3050 warnings"** -- **"Add DynamicallyAccessedMembers annotations"** -- **"Enable IsAotCompatible in my .csproj"** -- **"My project has trim analyzer warnings after upgrading to net8.0"** -- **"Annotate reflection code for the trimmer"** - -## When Not to Use This Skill - -Do not use this skill when the project exclusively targets .NET Framework (net4x), which does not support the trim/AOT analyzers. - -## Prerequisites - -An existing .NET project targeting net8.0 or later (or multi-targeting with at least one net8.0+ TFM) and the corresponding .NET SDK installed. - -## Background: What AOT Compatibility Means - -Native AOT and the IL trimmer perform static analysis to determine what code is reachable. Reflection can break this analysis because the trimmer can't see what types/members are accessed at runtime. The `IsAotCompatible` property enables analyzers that flag these issues as build warnings (ILXXXX codes). - -## Critical Rules - -### ❌ Never suppress warnings incorrectly - -- **NEVER** use `#pragma warning disable` for IL warnings. It hides warnings from the Roslyn analyzer at build time, but the IL linker and AOT compiler still see the issue. The code will fail at trim/publish time. -- **NEVER** use `[UnconditionalSuppressMessage]`. It tells both the analyzer AND the linker to ignore the warning, meaning the trimmer cannot verify safety. Raising an error at build time is always preferable to hiding the issue and having it silently break at runtime. - -### 💡 Preferred approaches - -- **Prefer** `[DynamicallyAccessedMembers]` annotations to flow type information through the call chain. -- **Prefer** refactoring to eliminate patterns that break annotation flow (e.g., boxing `Type` through `object[]`). -- **Use** `[RequiresUnreferencedCode]` / `[RequiresDynamicCode]` / `[RequiresAssemblyFiles]` to mark methods as fundamentally incompatible with trimming, propagating the requirement to callers. This surfaces the issue clearly rather than hiding it — callers must explicitly acknowledge the incompatibility. - -### Annotation flow is key - -The trimmer tracks `[DynamicallyAccessedMembers]` annotations through assignments, parameter passing, and return values. If this flow is broken (e.g., by boxing a `Type` into `object`, storing in an untyped collection, or casting through interfaces), the trimmer loses track and warns. The fix is to preserve the flow, not suppress the warning. - -## Step-by-Step Procedure - -> **Do not explore the codebase up-front.** The build warnings tell you exactly which files and lines need changes. Follow a tight loop: **build → pick a warning → open that file at that line → apply the fix recipe → rebuild**. Reading or analyzing source files beyond what a specific warning points you to is wasted effort and leads to timeouts. Let the compiler guide you. -> -> ❌ Do NOT run `find`, `ls`, or `grep` to understand the project structure before building. Do NOT read README, docs, or architecture files. Your first action should be Step 1 (enable AOT analysis), then build. - -### Step 1: Enable AOT analysis in the .csproj - -Add `IsAotCompatible`. If the project doesn't exclusively target net8.0+, add a TFM condition (AOT analysis requires net8.0+): - -```xml - - true - -``` - -This automatically sets `EnableTrimAnalyzer=true` and `EnableAotAnalyzer=true` for compatible TFMs. For multi-targeting projects (e.g., `netstandard2.0;net8.0`), the condition ensures no `NETSDK1210` warnings on older TFMs. - -### Step 2: Build and collect warnings - -```bash -dotnet build -f --no-incremental 2>&1 | grep 'IL[0-9]\{4\}' -``` - -Sort and deduplicate. Common warning codes: -- **IL2070**: Reflection call on a `Type` parameter missing `[DynamicallyAccessedMembers]` -- **IL2067**: Passing an unannotated `Type` to a method expecting `[DynamicallyAccessedMembers]` -- **IL2072**: Return value or extracted value missing annotation (often from unboxing) -- **IL2057**: `Type.GetType(string)` with a non-constant argument -- **IL2026**: Calling a method marked `[RequiresUnreferencedCode]` -- **IL2050**: P/invoke method with COM marshalling parameters -- **IL2075**: Return value flows into reflection without annotation -- **IL2091**: Generic argument missing `[DynamicallyAccessedMembers]` required by constraint -- **IL3000**: `Assembly.Location` returns empty string in single-file/AOT apps -- **IL3050**: Calling a method marked `[RequiresDynamicCode]` - -### Step 3: Triage warnings by code (do NOT read every file) - -Group the warnings from Step 2 by warning code and count them. **Do not open individual files yet.** Identify the top 1-2 patterns by count — these drive your fix strategy: - -| Pattern | Typical fix | -|---------|-------------| -| Many IL2026 + IL3050 from `JsonSerializer` | **Go to Strategy C immediately** — create a `JsonSerializerContext`, then batch-update all call sites | -| IL2070/IL2087 on `Type` parameters | Add `[DynamicallyAccessedMembers]` to the innermost method, then cascade outward | -| IL2067 passing unannotated `Type` | Annotate the parameter at the source | - -**In most real projects, IL2026/IL3050 from JsonSerializer dominate.** Start with Strategy C unless the warning breakdown clearly shows otherwise. After the batch JSON fix, handle remaining warnings with Strategies A–B. Only use Strategy D as a last resort. - -### Step 4: Fix warnings iteratively (innermost first) - -Work from the **innermost** reflection call outward. Each fix may cascade new warnings to callers. - -**Stay warning-driven.** For each warning, open only the file and line the compiler reported, identify the pattern, apply the matching fix recipe below, and move on. Do not scan the codebase for similar patterns or try to understand the full architecture — fix what the compiler tells you, rebuild, and let new warnings guide the next change. Fix a small batch of warnings (5-10), then rebuild immediately to check progress. - -**Use sub-agents when available.** If you can launch sub-agents (e.g., via a `task` tool), dispatch **multiple sub-agents in parallel** to edit different files simultaneously. Keep the main loop focused on building, parsing warnings, and dispatching — delegate actual file edits to sub-agents. For batch JSON updates, give each sub-agent 5-10 files to update in one prompt. **After 2 build-fix cycles, dispatch all remaining file edits to sub-agents in parallel — do not continue fixing files sequentially.** Example: - -> Update these files to use source-generated JSON: `src/Models/Resource.Serialization.cs`, `src/Models/Identity.Serialization.cs`, `src/Models/Plan.Serialization.cs`. In each file, replace `JsonSerializer.Serialize(writer, value)` with `JsonSerializer.Serialize(writer, value, MyProjectJsonContext.Default.TypeName)` and `JsonSerializer.Deserialize(ref reader)` with `JsonSerializer.Deserialize(ref reader, MyProjectJsonContext.Default.TypeName)`. Only edit the JsonSerializer call sites. - -#### Strategy A: Add `[DynamicallyAccessedMembers]` (preferred) - -When a method uses reflection on a `Type` parameter, annotate the parameter to tell the trimmer what members are needed: - -```csharp -using System.Diagnostics.CodeAnalysis; - -// Before (warns IL2070): -void Process(Type t) { - var method = t.GetMethod("Foo"); // trimmer can't verify -} - -// After (clean): -void Process([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) { - var method = t.GetMethod("Foo"); // trimmer preserves public methods -} -``` - -When you annotate a parameter, **all callers** must now pass properly annotated types. This cascades outward — follow each caller and annotate or refactor as needed. **The caller's annotation must include at least the same member types as the callee's.** If the callee requires `PublicConstructors | NonPublicConstructors`, the caller must specify the same or a superset — using only `NonPublicConstructors` will produce IL2091. - -#### Strategy B: Refactor to preserve annotation flow - -When annotation flow is broken by boxing (storing `Type` in `object`, `object[]`, or untyped collections), **refactor** to pass the `Type` directly: - -```csharp -// BROKEN: Type boxed into object[], annotation lost -void Process(object[] args) { - Type t = (Type)args[0]; // IL2072: annotation lost through boxing - Evaluate(t, ...); -} - -// FIXED: Pass Type as a separate, annotated parameter -void Process( - object[] args, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type calleeType, - ...) { - Evaluate(calleeType, ...); // annotation flows cleanly -} -``` - -Common patterns that break flow and how to fix them: -- **`object[]` parameter bags**: Extract the `Type` into a dedicated annotated parameter -- **Dictionary/List storage**: Use a typed field with annotation instead -- **Interface indirection**: Add annotation to the interface method's parameter -- **Property with boxing getter**: Annotate the property's return type - -#### Strategy C: Source-generated JSON serialization (batch fix) - -When most warnings are IL2026/IL3050 from `JsonSerializer.Serialize`/`Deserialize`, this is a single mechanical fix applied in bulk: - -1. **Collect affected types** — grep for all `JsonSerializer.Serialize` and `JsonSerializer.Deserialize` call sites. Extract the type being serialized (the `` in `Deserialize`, or the runtime type of the object in `Serialize`). - -2. **Create one `JsonSerializerContext`** with `[JsonSerializable]` for every type found. **Skip types from external packages** (e.g., `ResponseError` from `Azure.Core`) — they won't source-generate for types you don't own. Handle external types separately via Gotcha #1 below. - -```csharp -[JsonSerializerContext] -[JsonSerializable(typeof(ManagedServiceIdentity))] -[JsonSerializable(typeof(SystemData))] -// ... one attribute per type YOU OWN -// Do NOT add types from external packages (e.g., ResponseError) -internal partial class MyProjectJsonContext : JsonSerializerContext { } -``` - -3. **Batch-update all call sites** — do not read each file individually. Apply the pattern mechanically: - - `JsonSerializer.Serialize(obj)` → `JsonSerializer.Serialize(obj, MyProjectJsonContext.Default.TypeName)` - - `JsonSerializer.Deserialize(json)` → `JsonSerializer.Deserialize(json, MyProjectJsonContext.Default.TypeName)` - - Find and update all call sites in one pass: - ```bash - # Find all files with JsonSerializer calls - grep -rl 'JsonSerializer\.\(Serialize\|Deserialize\)' src/ --include='*.cs' - ``` - Then use sequential `edit` calls to apply the same transformation to every matching file. **Do not use `sed` for C# code** — generics like `Deserialize()` have angle brackets and nested parentheses that sed will mangle. - -4. **Build once** to verify. Remaining warnings will be non-serialization issues — handle those with Strategies A–B or D. - -#### Strategy D: `[RequiresUnreferencedCode]` (last resort) - -When a method fundamentally requires arbitrary reflection that cannot be statically described: - -```csharp -[RequiresUnreferencedCode("Loads plugins by name using Assembly.Load")] -public void LoadPlugin(string assemblyName) { - var asm = Assembly.Load(assemblyName); - // ... -} -``` - -This propagates to callers — they must also be annotated with `[RequiresUnreferencedCode]`. Use sparingly; it marks the entire call chain as trim-incompatible. - -### Step 5: Rebuild and repeat - -After each small batch of fixes (5-10 warnings), rebuild with `--no-incremental` and check for new warnings. **Do not attempt to fix all warnings before rebuilding** — frequent rebuilds catch mistakes early and reveal cascading warnings. Fixes cascade — annotating an inner method may surface warnings in its callers. Repeat until `0 Warning(s)`. - -### Step 6: Validate all TFMs - -Build all target frameworks to ensure: -- **0 IL warnings** on net8.0+ TFMs -- **No NETSDK1210 warnings** (the `IsAotCompatible` condition handles this) -- **Clean builds** on older TFMs (netstandard2.0, net472, etc.) - -```bash -dotnet build # builds all TFMs -``` - -## Stop Signals - -- **Do not analyze more than 2-3 representative files per warning pattern.** After identifying the fix for a pattern, apply it to all matching files without reading each one first. -- **Start fixing after one build.** Do not do a second analysis pass — begin implementing fixes for the most common warning pattern immediately after Step 3 triage. -- Stop after achieving **0 IL warnings** for net8.0+ TFMs. Don't optimize or refactor already-clean annotations. -- If a warning requires **architectural refactoring** beyond annotation flow fixes (e.g., replacing an entire serialization layer), document it and stop — don't rewrite large subsystems. -- Limit to **3 build-fix iterations** per warning. If annotation flow doesn't resolve it after 3 attempts, escalate to `[RequiresUnreferencedCode]`. -- Don't chase warnings in **third-party dependencies** you can't modify. Note them and move on. -- If the user asked a scoped question (e.g., "fix warnings in this file"), don't expand to the entire project. - -## Polyfills for Older TFMs - -For multi-targeting projects that include netstandard2.0 or net472, you need polyfills for `DynamicallyAccessedMembersAttribute` and related types. See [references/polyfills.md](references/polyfills.md). - -## Common Gotchas - -1. **External types without AOT-safe serialization**: When a type comes from a dependency you can't modify (e.g., `ResponseError` from `Azure.Core`) and it lacks a source-generated serializer, `Options.GetConverter()` is reflection-based and will produce IL warnings. First check if the type implements `IJsonModel` (common in Azure SDK) — if so, bypass `JsonSerializer` entirely: - -```csharp -// Before (IL2026 — JsonSerializer uses reflection): -JsonSerializer.Serialize(writer, errorValue); - -// After (AOT-safe — uses IJsonModel directly): -((IJsonModel)errorValue).Write(writer, ModelReaderWriterOptions.Json); - -// For deserialization: -var error = ((IJsonModel)new ResponseError()).Create(ref reader, ModelReaderWriterOptions.Json); -``` - -Do **not** add the external type to your `JsonSerializerContext` — it won't source-generate for types you don't own. If the type doesn't implement `IJsonModel`, write a custom `JsonConverter` with manual `Utf8JsonReader`/`Utf8JsonWriter` logic and register it via `[JsonSourceGenerationOptions]` on your context. - -2. **Serialization libraries**: Most reflection-based serializers (e.g., `Newtonsoft.Json`, `XmlSerializer`) are not AOT-compatible. Migrate to a source-generation-based serializer such as `System.Text.Json` with a `JsonSerializerContext`. If migration is not feasible, mark the serialization call site with `[RequiresUnreferencedCode]`. - -3. **Shared projects / projitems**: When source is shared between multiple projects via ``, annotations added to shared code affect ALL consuming projects. Verify that all consumers still build cleanly. - -## References - -[Limitations](https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/?tabs=windows%2Cnet8#limitations-of-native-aot-deployment) -[Conceptual: Understanding trimming](https://learn.microsoft.com/en-us/dotnet/core/deploying/trimming/trimming-concepts) -[How-to: trim compat](https://learn.microsoft.com/en-us/dotnet/core/deploying/trimming/fixing-warnings) - -## Checklist - -- [ ] Added `` with TFM condition to .csproj -- [ ] Built with AOT analyzers enabled (net8.0+ TFM) -- [ ] Fixed all IL warnings via annotations or refactoring -- [ ] No `#pragma warning disable` or `[UnconditionalSuppressMessage]` used for any IL warning -- [ ] Polyfills present for older TFMs if needed -- [ ] All target frameworks build with 0 warnings -- [ ] Verified shared/linked source doesn't break sibling projects diff --git a/plugins/dotnet-upgrade/skills/dotnet-aot-compat/references/polyfills.md b/plugins/dotnet-upgrade/skills/dotnet-aot-compat/references/polyfills.md deleted file mode 100644 index a577f2e2c6..0000000000 --- a/plugins/dotnet-upgrade/skills/dotnet-aot-compat/references/polyfills.md +++ /dev/null @@ -1,43 +0,0 @@ -# Polyfills for Older TFMs - -`DynamicallyAccessedMembersAttribute` shipped in .NET 5. For projects targeting netstandard2.0 or net472, you need a polyfill. The trimmer recognizes the attribute by name, so a local copy works: - -```csharp -#if !NET -namespace System.Diagnostics.CodeAnalysis -{ - [AttributeUsage(AttributeTargets.Field | AttributeTargets.ReturnValue | - AttributeTargets.GenericParameter | AttributeTargets.Parameter | - AttributeTargets.Property, Inherited = false)] - internal sealed class DynamicallyAccessedMembersAttribute : Attribute - { - public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) - => MemberTypes = memberTypes; - public DynamicallyAccessedMemberTypes MemberTypes { get; } - } - - [Flags] - internal enum DynamicallyAccessedMemberTypes - { - None = 0, - PublicParameterlessConstructor = 0x0001, - PublicConstructors = 0x0002 | PublicParameterlessConstructor, - NonPublicConstructors = 0x0004, - PublicMethods = 0x0008, - NonPublicMethods = 0x0010, - PublicFields = 0x0020, - NonPublicFields = 0x0040, - PublicNestedTypes = 0x0080, - NonPublicNestedTypes = 0x0100, - PublicProperties = 0x0200, - NonPublicProperties = 0x0400, - PublicEvents = 0x0800, - NonPublicEvents = 0x1000, - Interfaces = 0x2000, - All = ~None // Discouraged — prefer specific flags - } -} -#endif -``` - -Similarly for `RequiresUnreferencedCodeAttribute` and `UnconditionalSuppressMessageAttribute` if needed on older TFMs. diff --git a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/SKILL.md b/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/SKILL.md deleted file mode 100644 index dd50f5a1a9..0000000000 --- a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/SKILL.md +++ /dev/null @@ -1,274 +0,0 @@ ---- -name: migrate-dotnet9-to-dotnet10 -description: > - Migrate a .NET 9 project or solution to .NET 10 and resolve all breaking changes. - USE FOR: upgrading TargetFramework from net9.0 to net10.0, fixing build errors - after updating the .NET 10 SDK, resolving source and behavioral changes in - .NET 10 / C# 14 / ASP.NET Core 10 / EF Core 10, updating Dockerfiles for - Debian-to-Ubuntu base images, resolving obsoletion warnings - (SYSLIB0058-SYSLIB0062), adapting to SDK/NuGet changes (NU1510, - PrunePackageReference), migrating System.Linq.Async to built-in - AsyncEnumerable, fixing OpenApi v2 API changes, cryptography renames, and - C# 14 compiler changes (field keyword, extension keyword, span overloads). - DO NOT USE FOR: .NET Framework migrations, upgrading from .NET 8 or earlier - (use migrate-dotnet8-to-dotnet9 first), greenfield .NET 10 projects, or - cosmetic modernization. - LOADS REFERENCES: csharp-compiler, core-libraries, sdk-msbuild (always); - aspnet-core, efcore, cryptography, extensions-hosting, - serialization-networking, winforms-wpf, containers-interop (selective). -license: MIT ---- - -# .NET 9 → .NET 10 Migration - -Migrate a .NET 9 project or solution to .NET 10, systematically resolving all breaking changes. The outcome is a project targeting `net10.0` that builds cleanly, passes tests, and accounts for every behavioral, source-incompatible, and binary-incompatible change introduced in the .NET 10 release. - -## When to Use - -- Upgrading `TargetFramework` from `net9.0` to `net10.0` -- Resolving build errors or new warnings after updating the .NET 10 SDK -- Adapting to behavioral changes in .NET 10 runtime, ASP.NET Core 10, or EF Core 10 -- Updating CI/CD pipelines, Dockerfiles, or deployment scripts for .NET 10 -- Migrating from the community `System.Linq.Async` package to the built-in `System.Linq.AsyncEnumerable` - -## When Not to Use - -- The project already targets `net10.0` and builds cleanly — migration is done -- Upgrading from .NET 8 or earlier — use the `migrate-dotnet8-to-dotnet9` skill first to reach `net9.0`, then return to this skill for the `net9.0` → `net10.0` migration -- Migrating from .NET Framework — that is a separate, larger effort -- Greenfield projects that start on .NET 10 (no migration needed) - -## Inputs - -| Input | Required | Description | -|-------|----------|-------------| -| Project or solution path | Yes | The `.csproj`, `.sln`, or `.slnx` entry point to migrate | -| Build command | No | How to build (e.g., `dotnet build`, a repo build script). Auto-detect if not provided | -| Test command | No | How to run tests (e.g., `dotnet test`). Auto-detect if not provided | -| Project type hints | No | Whether the project uses ASP.NET Core, EF Core, WinForms, WPF, containers, etc. Auto-detect from PackageReferences and SDK attributes if not provided | - -## Workflow - -> **Answer directly from the loaded reference documents.** Do not search the filesystem or fetch web pages for breaking change information — the references contain the authoritative details. Focus on identifying which breaking changes apply and providing concrete fixes. **Exception:** If you suspect a security vulnerability (CVE) may apply to the project's dependencies, check for published security advisories — the reference documents may not cover post-publication CVEs. -> -> **Commit strategy:** Commit at each logical boundary — after updating the TFM (Step 2), after resolving build errors (Step 3), after addressing behavioral changes (Step 4), and after updating infrastructure (Step 5). This keeps each commit focused and reviewable. - -### Step 1: Assess the project - -1. Identify how the project is built and tested. Look for build scripts, `.sln`/`.slnx` files, or individual `.csproj` files. -2. Run `dotnet --version` to confirm the .NET 10 SDK is installed. If it is not, stop and inform the user. -3. Determine which technology areas the project uses by examining: - - **SDK attribute**: `Microsoft.NET.Sdk.Web` → ASP.NET Core; `Microsoft.NET.Sdk.WindowsDesktop` with `` or `` → WPF/WinForms - - **PackageReferences**: `Microsoft.EntityFrameworkCore.*` → EF Core; `Microsoft.Data.Sqlite` → Sqlite; `Microsoft.Extensions.Hosting` → Generic Host / BackgroundService - - **Dockerfile presence** → Container changes relevant - - **P/Invoke or native interop usage** → Interop changes relevant - - **`System.Linq.Async` package reference** → AsyncEnumerable migration needed - - **`System.Text.Json` usage with polymorphism** → Serialization changes relevant -4. Record which reference documents are relevant (see the reference loading table in Step 3). -5. Do a **clean build** (`dotnet build --no-incremental` or delete `bin`/`obj`) on the current `net9.0` target to establish a clean baseline. Record any pre-existing warnings. - -### Step 2: Update the Target Framework - -1. In each `.csproj` (or `Directory.Build.props` if centralized), change: - ```xml - net9.0 - ``` - to: - ```xml - net10.0 - ``` - For multi-targeted projects, add `net10.0` to `` or replace `net9.0`. - -2. Update all `Microsoft.Extensions.*`, `Microsoft.AspNetCore.*`, `Microsoft.EntityFrameworkCore.*`, and other Microsoft package references to their 10.0.x versions. If using Central Package Management (`Directory.Packages.props`), update versions there. - -3. Run `dotnet restore`. Watch for: - - **NU1510**: Direct references pruned by NuGet — the package may be included in the shared framework now. Remove the explicit `` if so. - - **PackageReference without a version now raises an error** — every `` must have a `Version` (or use CPM). - - **NuGet auditing of transitive packages** (`dotnet restore` now audits transitive deps) — review any new vulnerability warnings. - -4. Run a clean build. Collect all errors and new warnings. These will be addressed in Step 3. - -### Step 3: Resolve build errors and source-incompatible changes - -Work through compilation errors and new warnings systematically. Load the appropriate reference documents based on the project type: - -| If the project uses… | Load reference | -|-----------------------|----------------| -| Any .NET 10 project | `references/csharp-compiler-dotnet9to10.md` | -| Any .NET 10 project | `references/core-libraries-dotnet9to10.md` | -| Any .NET 10 project | `references/sdk-msbuild-dotnet9to10.md` | -| ASP.NET Core | `references/aspnet-core-dotnet9to10.md` | -| Entity Framework Core | `references/efcore-dotnet9to10.md` | -| Cryptography APIs | `references/cryptography-dotnet9to10.md` | -| Microsoft.Extensions.Hosting, BackgroundService, configuration | `references/extensions-hosting-dotnet9to10.md` | -| System.Text.Json, XmlSerializer, HttpClient, MailAddress, Uri | `references/serialization-networking-dotnet9to10.md` | -| Windows Forms or WPF | `references/winforms-wpf-dotnet9to10.md` | -| Docker containers, single-file apps, native interop | `references/containers-interop-dotnet9to10.md` | - -**Common source-incompatible changes to check for:** - -1. **`System.Linq.Async` conflicts** — Remove the `System.Linq.Async` package reference or upgrade to v7.0.0. If consumed transitively, add `compile`. Rename `SelectAwait` calls to `Select` where needed. - -2. **New obsoletion warnings (SYSLIB0058–SYSLIB0062)**: - - `SYSLIB0058`: Replace `SslStream.KeyExchangeAlgorithm`/`CipherAlgorithm`/`HashAlgorithm` with `NegotiatedCipherSuite` — if the old properties were used to reject weak TLS ciphers, preserve equivalent validation logic using the new API - - `SYSLIB0059`: Replace `SystemEvents.EventsThreadShutdown` with `AppDomain.ProcessExit` - - `SYSLIB0060`: Replace `Rfc2898DeriveBytes` constructors with `Rfc2898DeriveBytes.Pbkdf2` - - `SYSLIB0061`: Replace `Queryable.MaxBy`/`MinBy` overloads taking `IComparer` with ones taking `IComparer` - - `SYSLIB0062`: Replace `XsltSettings.EnableScript` usage - -3. **C# 14 `field` keyword in property accessors** — The identifier `field` is now a contextual keyword inside property `get`/`set`/`init` accessors. Local variables named `field` cause CS9272 (error). Class members named `field` referenced without `this.` cause CS9258 (warning). Fix by renaming (e.g., `fieldValue`) or escaping with `@field`. See `references/csharp-compiler-dotnet9to10.md`. - -4. **C# 14 `extension` contextual keyword** — Types, aliases, or type parameters named `extension` are disallowed. Rename or escape with `@extension`. - -5. **C# 14 overload resolution with span parameters** — Expression trees containing `.Contains()` on arrays may now bind to `MemoryExtensions.Contains` instead of `Enumerable.Contains`. `Enumerable.Reverse` on arrays may resolve to the in-place `Span` extension. Fix by casting to `IEnumerable`, using `.AsEnumerable()`, or explicit static invocations. See `references/csharp-compiler-dotnet9to10.md` for full details. - -6. **ASP.NET Core obsoletions** (if applicable): - - `WebHostBuilder`, `IWebHost`, `WebHost` are obsolete — migrate to `Host.CreateDefaultBuilder` or `WebApplication.CreateBuilder` - - `IActionContextAccessor` / `ActionContextAccessor` obsolete - - `WithOpenApi` extension method deprecated - - `IncludeOpenAPIAnalyzers` property deprecated - - `IPNetwork` and `ForwardedHeadersOptions.KnownNetworks` obsolete - - Razor runtime compilation is obsolete - - `Microsoft.Extensions.ApiDescription.Client` package deprecated - - **`Microsoft.OpenApi` v2.x breaking changes** — `Microsoft.AspNetCore.OpenApi 10.0` pulls in `Microsoft.OpenApi` v2.x which restructures namespaces and models. `OpenApiString`/`OpenApiAny` types are removed (use `JsonNode`), `OpenApiSecurityScheme.Reference` replaced by `OpenApiSecuritySchemeReference`, collections on OpenAPI model objects may be null, and `OpenApiSchema.Nullable` is removed. See `references/aspnet-core-dotnet9to10.md` for migration patterns. - -7. **SDK changes**: - - `dotnet new sln` now defaults to SLNX format — use `--format sln` if the old format is needed - - Double quotes in file-level directives are disallowed - - `dnx.ps1` removed from .NET SDK - - `project.json` no longer supported in `dotnet restore` - -8. **EF Core source changes** (if applicable) — See `references/efcore-dotnet9to10.md` for: - - `ExecuteUpdateAsync` now accepts a regular lambda (expression tree construction code must be rewritten) - - `IDiscriminatorPropertySetConvention` signature changed - - `IRelationalCommandDiagnosticsLogger` methods add `logCommandText` parameter - -9. **WinForms/WPF source changes** (if applicable): - - Applications referencing both WPF and WinForms must disambiguate `MenuItem` and `ContextMenu` types - - Renamed parameter in `HtmlElement.InsertAdjacentElement` - - Empty `ColumnDefinitions` and `RowDefinitions` are disallowed in WPF - -10. **Cryptography source changes** (if applicable): - - `MLDsa` and `SlhDsa` members renamed from `SecretKey` to `PrivateKey` (e.g., `ExportMLDsaSecretKey` → `ExportMLDsaPrivateKey`, `SecretKeySizeInBytes` → `PrivateKeySizeInBytes`) - - `Rfc2898DeriveBytes` constructors are obsolete (SYSLIB0060) — replace with static `Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, hashAlgorithm, outputLength)` - - `CoseSigner.Key` can now be null — check for null before use - - `X509Certificate.GetKeyAlgorithmParameters()` and `PublicKey.EncodedParameters` can return null - - Environment variable renamed from `CLR_OPENSSL_VERSION_OVERRIDE` to `DOTNET_OPENSSL_VERSION_OVERRIDE` - -Build again after each batch of fixes. Repeat until the build is clean. - -### Step 4: Address behavioral changes - -Behavioral changes do not cause build errors but may change runtime behavior. Review each applicable item and determine whether the previous behavior was relied upon. - -**High-impact behavioral changes (check first):** - -1. **SIGTERM signal handling removed** — The .NET runtime no longer registers default SIGTERM handlers. If you rely on `AppDomain.ProcessExit` or `AssemblyLoadContext.Unloading` being raised on SIGTERM: - - ASP.NET Core and Generic Host apps are unaffected (they register their own handlers) - - Console apps and containerized apps without Generic Host must register `PosixSignalRegistration.Create(PosixSignal.SIGTERM, _ => Environment.Exit(0))` explicitly - -2. **BackgroundService.ExecuteAsync runs entirely on a background thread** — The synchronous portion before the first `await` no longer blocks startup. If startup ordering matters, move that code to `StartAsync` or the constructor, or implement `IHostedLifecycleService`. - -3. **Configuration null values are now preserved** — JSON `null` values are no longer converted to empty strings. Properties initialized with non-default values will be overwritten with `null`. Review configuration binding code. - -4. **Microsoft.Data.Sqlite DateTimeOffset changes** (all High impact): - - `GetDateTimeOffset` without an offset now assumes UTC (previously assumed local) - - Writing `DateTimeOffset` into REAL columns now converts to UTC first - - `GetDateTime` with an offset now returns UTC with `DateTimeKind.Utc` - - Mitigation: `AppContext.SetSwitch("Microsoft.Data.Sqlite.Pre10TimeZoneHandling", true)` as a temporary workaround - -5. **EF Core parameterized collections** — `.Contains()` on collections now uses multiple scalar parameters instead of JSON/OPENJSON. May affect query performance for large collections. Mitigation: `UseParameterizedCollectionMode(ParameterTranslationMode.Parameter)` to revert. - -6. **EF Core JSON data type on Azure SQL** — Azure SQL and compatibility level ≥170 now use the `json` data type instead of `nvarchar(max)`. A migration will be generated to alter existing columns. Mitigation: set compatibility level to 160 or use `HasColumnType("nvarchar(max)")` explicitly. - -7. **System.Text.Json property name conflict validation** — Polymorphic types with properties conflicting with metadata names (`$type`, `$id`, `$ref`) now throw `InvalidOperationException`. Add `[JsonIgnore]` to conflicting properties. - -**Other behavioral changes to review:** - -- `BufferedStream.WriteByte` no longer implicitly flushes — add explicit `Flush()` calls if needed -- Default trace context propagator updated to W3C standard -- `DriveInfo.DriveFormat` returns actual Linux filesystem type names -- LDAP `DirectoryControl` parsing is more stringent -- Default .NET container images switched from Debian to Ubuntu (Debian images no longer shipped) -- Single-file apps no longer look for native libraries in executable directory by default -- `DllImportSearchPath.AssemblyDirectory` only searches the assembly directory -- `MailAddress` enforces validation for consecutive dots -- Streaming HTTP responses enabled by default in browser HTTP clients -- `Uri` length limits removed — add explicit length validation if `Uri` was used to reject oversized input from untrusted sources -- Cookie login redirects disabled for known API endpoints (ASP.NET Core) -- `XmlSerializer` no longer ignores `[Obsolete]` properties — audit obsolete properties for sensitive data and add `[XmlIgnore]` to prevent unintended data exposure -- `dotnet restore` audits transitive packages -- `dotnet watch` logs to stderr instead of stdout -- `dotnet` CLI commands log non-command-relevant data to stderr -- Various NuGet behavioral changes (see `references/sdk-msbuild-dotnet9to10.md`) -- `StatusStrip` uses System RenderMode by default (WinForms) -- `TreeView` checkbox image truncation fix (WinForms) -- `DynamicResource` incorrect usage causes crash (WPF) - -### Step 5: Update infrastructure - -1. **Dockerfiles**: Update base images. Default tags now use Ubuntu instead of Debian. Debian images are no longer shipped for .NET 10. - ```dockerfile - # Before - FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build - FROM mcr.microsoft.com/dotnet/aspnet:9.0 - # After - FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build - FROM mcr.microsoft.com/dotnet/aspnet:10.0 - ``` - -2. **CI/CD pipelines**: Update SDK version references. If using `global.json`, update: - ```json - { - "sdk": { - "version": "10.0.100" - } - } - ``` - -3. **Environment variables renamed**: - - `DOTNET_OPENSSL_VERSION_OVERRIDE` replaces the old name - - `DOTNET_ICU_VERSION_OVERRIDE` replaces the old name - - `NUGET_ENABLE_ENHANCED_HTTP_RETRY` has been removed - -4. **OpenSSL requirements**: OpenSSL 1.1.1 or later is now required on Unix. OpenSSL cryptographic primitives are no longer supported on macOS. - -5. **Solution file format**: If `dotnet new sln` is used in scripts, note it now generates SLNX format. Pass `--format sln` if the old format is needed. - -### Step 6: Verify - -1. Run a full clean build: `dotnet build --no-incremental` -2. Run all tests: `dotnet test` -3. If the application is containerized, build and test the container image -4. Smoke-test the application, paying special attention to: - - Signal handling / graceful shutdown behavior - - Background services startup ordering - - Configuration binding with null values - - Date/time handling with Sqlite - - JSON serialization with polymorphic types - - EF Core queries using `.Contains()` on collections -5. **Security review** — verify that the migration has not weakened security controls: - - TLS cipher validation logic is preserved after `SslStream` API migration (SYSLIB0058) - - Obsolete properties containing sensitive data are excluded from serialization (`[XmlIgnore]`, `[JsonIgnore]`) - - Input validation still rejects oversized URIs if `Uri` was used as a length gate - - Exception handlers emit security-relevant telemetry (auth failures, access violations) before returning `true` - - Connection strings set an explicit `Application Name` that does not leak version info - - `dotnet restore` vulnerability audit findings are addressed, not suppressed -6. Review the diff and ensure no unintended behavioral changes were introduced - -## Reference Documents - -The `references/` folder contains detailed breaking change information organized by technology area. Load only the references relevant to the project being migrated: - -| Reference file | When to load | -|----------------|-------------| -| `references/csharp-compiler-dotnet9to10.md` | Always (C# 14 compiler breaking changes — field keyword, extension keyword, span overloads) | -| `references/core-libraries-dotnet9to10.md` | Always (applies to all .NET 10 projects) | -| `references/sdk-msbuild-dotnet9to10.md` | Always (SDK and build tooling changes) | -| `references/aspnet-core-dotnet9to10.md` | Project uses ASP.NET Core | -| `references/efcore-dotnet9to10.md` | Project uses Entity Framework Core or Microsoft.Data.Sqlite | -| `references/cryptography-dotnet9to10.md` | Project uses System.Security.Cryptography or X.509 certificates | -| `references/extensions-hosting-dotnet9to10.md` | Project uses Generic Host, BackgroundService, or Microsoft.Extensions.Configuration | -| `references/serialization-networking-dotnet9to10.md` | Project uses System.Text.Json, XmlSerializer, HttpClient, or networking APIs | -| `references/winforms-wpf-dotnet9to10.md` | Project uses Windows Forms or WPF | -| `references/containers-interop-dotnet9to10.md` | Project uses Docker containers, single-file publishing, or native interop (P/Invoke) | diff --git a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/aspnet-core-dotnet9to10.md b/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/aspnet-core-dotnet9to10.md deleted file mode 100644 index efd66a260c..0000000000 --- a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/aspnet-core-dotnet9to10.md +++ /dev/null @@ -1,140 +0,0 @@ -# ASP.NET Core 10 Breaking Changes - -These changes affect projects using ASP.NET Core (Microsoft.NET.Sdk.Web). - -## Source-Incompatible Changes - -### WebHostBuilder, IWebHost, and WebHost are obsolete - -The legacy `WebHostBuilder` and related APIs are now marked obsolete. Migrate to the modern hosting model: - -```csharp -// Before (.NET 9) -var host = new WebHostBuilder() - .UseKestrel() - .UseStartup() - .Build(); - -// After (.NET 10) -var builder = WebApplication.CreateBuilder(args); -// Configure services in builder.Services -var app = builder.Build(); -// Configure middleware pipeline -app.Run(); -``` - -If still using `Startup` classes, the `WebApplication` model supports them via `builder.Host.ConfigureWebHostDefaults(...)` or inline configuration. - -### IActionContextAccessor and ActionContextAccessor are obsolete - -These types are obsolete. Access `ActionContext` through dependency injection or the `HttpContext` instead: -```csharp -// Before -services.AddSingleton(); - -// After — use IHttpContextAccessor or inject ActionContext directly in filters/middleware -``` - -### Deprecation of WithOpenApi extension method - -The `WithOpenApi()` extension method is deprecated. Use the built-in OpenAPI document generation in ASP.NET Core 10 instead. - -### IncludeOpenAPIAnalyzers property and MVC API analyzers deprecated - -The `` MSBuild property is deprecated. Remove it from `.csproj` files. The analyzers are no longer needed with the new OpenAPI infrastructure. - -### IPNetwork and ForwardedHeadersOptions.KnownNetworks are obsolete - -`IPNetwork` is obsolete. Use `System.Net.IPNetwork` (the new runtime type) and the new `KnownIpNetworks` property instead: -```csharp -// Before -app.UseForwardedHeaders(new ForwardedHeadersOptions -{ - KnownNetworks = { new IPNetwork(IPAddress.Parse("10.0.0.0"), 8) } -}); - -// After — use KnownIpNetworks with the new System.Net.IPNetwork type -app.UseForwardedHeaders(new ForwardedHeadersOptions -{ - KnownIpNetworks = { new System.Net.IPNetwork(IPAddress.Parse("10.0.0.0"), 8) } -}); -``` - -### Razor runtime compilation is obsolete - -`AddRazorRuntimeCompilation()` is obsolete. Razor views and pages should be precompiled. For development, use hot reload (`dotnet watch`) instead. - -### Microsoft.Extensions.ApiDescription.Client package deprecated - -The `Microsoft.Extensions.ApiDescription.Client` package is deprecated. Use the built-in OpenAPI client generation tooling instead. - -### Microsoft.OpenApi 2.x breaking API changes - -`Microsoft.AspNetCore.OpenApi 10.0` depends on `Microsoft.OpenApi` v2.x (from [`microsoft/OpenAPI.NET`](https://github.com/microsoft/OpenAPI.NET) repo), which has significant breaking API changes from v1.x. Projects that customize OpenAPI document generation using transformers or directly manipulate OpenAPI models will need code changes. Note: no official v1→v2 migration guide exists; the repo has a [v3 upgrade guide](https://github.com/microsoft/OpenAPI.NET/blob/main/docs/upgrade-guide-3.md) only. These changes are also not listed on the ASP.NET Core 10 breaking changes page. - -**Namespace changes — `Microsoft.OpenApi.Models` and `Microsoft.OpenApi.Any` are completely removed:** - -All types previously in these namespaces (`OpenApiSchema`, `OpenApiParameter`, `OpenApiResponse`, `OpenApiSecurityScheme`, etc.) have moved to the root `Microsoft.OpenApi` namespace. Replace all `using Microsoft.OpenApi.Models;` and `using Microsoft.OpenApi.Any;` with `using Microsoft.OpenApi;`. - -```csharp -// Before (.NET 9 — Microsoft.OpenApi v1.x) -using Microsoft.OpenApi.Any; -using Microsoft.OpenApi.Models; - -// After (.NET 10 — Microsoft.OpenApi v2.x) -using Microsoft.OpenApi; // ALL model types are here now -using System.Text.Json.Nodes; // replaces OpenApiAny types -``` - -**Key API changes:** - -1. **`OpenApiString` / `OpenApiAny` types removed** — Use `System.Text.Json.Nodes.JsonNode` instead: - ```csharp - // Before - parameter.Schema.Example = new OpenApiString("1.0"); - // After - parameter.Schema.Example = JsonNode.Parse("\"1.0\""); - ``` - -2. **`OpenApiSecurityScheme.Reference` replaced** — Use `OpenApiSecuritySchemeReference` directly: - ```csharp - // Before - var scheme = new OpenApiSecurityScheme - { - Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } - }; - // After - var scheme = new OpenApiSecuritySchemeReference("oauth2", null); - ``` - -3. **Collections now nullable** — `operation.Parameters`, `operation.Responses`, `document.Components.SecuritySchemes`, and other collection properties may be null and must be checked or initialized: - ```csharp - operation.Responses ??= new OpenApiResponses(); - operation.Parameters?.FirstOrDefault(p => p.Name == "api-version"); - document.Components ??= new(); - document.Components.SecuritySchemes ??= new Dictionary(); - ``` - -4. **`OpenApiSchema.Nullable` removed** — OpenAPI 3.1 uses JSON Schema `type: ["string", "null"]` instead of `nullable: true`. Schema transformers that set `.Nullable = false` can be removed. - -5. **Security requirement values require `List`** — Implicit conversion from `string[]` may not work: - ```csharp - // Before - [oAuthScheme] = scopes - // After - [oAuthScheme] = scopes.ToList() - ``` - -6. **Interface types in some positions** — Some properties now use interfaces (e.g., `IOpenApiSecurityScheme` instead of `OpenApiSecurityScheme`). Check for compilation errors in transformer code. - -## Behavioral Changes - -### Cookie login redirects disabled for known API endpoints - -ASP.NET Core no longer redirects to login pages for requests to known API endpoints (e.g., those returning `ProblemDetails`). Instead, a `401` status code is returned directly. This is controlled by `IApiEndpointMetadata`, which is automatically applied to endpoints with `[ApiController]`, minimal API endpoints that read/write JSON, SignalR hubs, and endpoints returning `TypedResults`. - -This is generally the desired behavior for APIs, but may affect apps that relied on the redirect for API calls. To influence this behavior, you can manually add or check for `IApiEndpointMetadata` on specific endpoints. - -### Exception diagnostics suppressed when TryHandleAsync returns true - -**Security consideration:** When `IExceptionHandler.TryHandleAsync` returns `true`, the exception diagnostics middleware no longer emits diagnostic events for that exception. If handled exceptions include security-relevant events (authentication failures, authorization violations, injection attempts), suppressing diagnostics could create blind spots in security monitoring and audit logging. Ensure your exception handler explicitly emits security-relevant telemetry before returning `true`. diff --git a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/containers-interop-dotnet9to10.md b/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/containers-interop-dotnet9to10.md deleted file mode 100644 index 40d93c8967..0000000000 --- a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/containers-interop-dotnet9to10.md +++ /dev/null @@ -1,63 +0,0 @@ -# Containers, Interop, and Deployment Breaking Changes (.NET 10) - -These changes affect Docker containers, single-file apps, native interop (P/Invoke), and deployment scenarios. - -## Containers - -### Default .NET images use Ubuntu (Debian images discontinued) - -**Impact: Medium.** Default .NET container image tags now reference Ubuntu 24.04 (Noble Numbat) instead of Debian. Debian-based images are no longer provided for .NET 10. - -```dockerfile -# .NET 10 images — all Ubuntu-based -FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build -FROM mcr.microsoft.com/dotnet/aspnet:10.0 -FROM mcr.microsoft.com/dotnet/runtime:10.0 - -# Explicit Ubuntu tag (same as default) -FROM mcr.microsoft.com/dotnet/sdk:10.0-noble -``` - -**What to check:** -- Dockerfile `RUN apt-get` commands — Ubuntu and Debian share `apt` but may differ in available packages and versions -- Native library dependencies that were Debian-specific -- Custom base image layers that assumed Debian -- CI/CD scripts that referenced Debian-specific image tags - -**If you need Debian:** Create custom images following [Microsoft's guide for installing .NET in a Dockerfile](https://github.com/dotnet/dotnet-docker/blob/main/documentation/scenarios/installing-dotnet.md). - -## Interop - -### Single-file apps no longer look for native libraries in executable directory - -In single-file apps, the application directory is no longer automatically added to `NATIVE_DLL_SEARCH_DIRECTORIES`. The directory is only searched when `DllImportSearchPath.AssemblyDirectory` is included in the search paths (which is the default for P/Invokes without explicit search paths). - -**Breaking scenario:** P/Invokes with `[DefaultDllImportSearchPaths]` that explicitly exclude `AssemblyDirectory`: -```csharp -// This no longer finds "lib" in the app directory: -[DllImport("lib")] -[DefaultDllImportSearchPaths(DllImportSearchPath.System32)] -static extern void Method(); - -// Fix: Add AssemblyDirectory to the search paths: -[DllImport("lib")] -[DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] -static extern void Method(); -``` - -For NativeAOT on non-Windows, the `rpath` is no longer set to the application directory. Add explicit linker arguments if needed. - -### DllImportSearchPath.AssemblyDirectory only searches the assembly directory - -`DllImportSearchPath.AssemblyDirectory` now strictly searches only the assembly directory, not additional directories that were previously included. - -### Casting IDispatchEx COM object to IReflect fails - -Casting a COM object that implements `IDispatchEx` to `IReflect` now fails. Use `dynamic` or explicit COM interop interfaces instead. - -## Other Changes - -- **Globalization**: Environment variable renamed to `DOTNET_ICU_VERSION_OVERRIDE` -- **Reflection**: `[DynamicallyAccessedMembers]` annotations on `IReflect.InvokeMember`, `Type.FindMembers` are more restrictive (new trim warnings possible) -- **Reflection**: `Type.MakeGenericSignatureType` arguments validated more strictly -- **VS Code**: `dotnet.acquire` API no longer always downloads latest — pin specific versions diff --git a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/core-libraries-dotnet9to10.md b/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/core-libraries-dotnet9to10.md deleted file mode 100644 index 195962b80d..0000000000 --- a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/core-libraries-dotnet9to10.md +++ /dev/null @@ -1,93 +0,0 @@ -# Core .NET Libraries Breaking Changes (.NET 10) - -These breaking changes affect all .NET 10 projects regardless of application type. - -## Source-Incompatible Changes - -### System.Linq.AsyncEnumerable included in core libraries - -.NET 10 adds `System.Linq.AsyncEnumerable` with full LINQ support for `IAsyncEnumerable`, replacing the community `System.Linq.Async` NuGet package. Projects referencing `System.Linq.Async` will get ambiguity errors. - -**Fix:** -- Remove the `System.Linq.Async` package reference, or upgrade to v7.0.0 -- If consumed transitively, suppress with ``: - ```xml - - compile - - ``` -- Rename `SelectAwait` calls to `Select` where the new API uses a different name - -### API obsoletions (SYSLIB0058–SYSLIB0062) - -| Diagnostic | What's obsolete | Replacement | -|------------|----------------|-------------| -| SYSLIB0058 | `SslStream.KeyExchangeAlgorithm`, `CipherAlgorithm`, `HashAlgorithm` and their strength properties | `SslStream.NegotiatedCipherSuite` — **Security note:** if existing code used these properties to reject weak ciphers (e.g., RC4, 3DES, NULL), ensure equivalent validation is preserved using `NegotiatedCipherSuite` | -| SYSLIB0059 | `SystemEvents.EventsThreadShutdown` | `AppDomain.ProcessExit` | -| SYSLIB0060 | `Rfc2898DeriveBytes` constructors | `Rfc2898DeriveBytes.Pbkdf2` static method | -| SYSLIB0061 | `Queryable.MaxBy`/`MinBy` overloads with `IComparer` | New overloads with `IComparer` | -| SYSLIB0062 | `XsltSettings.EnableScript` | N/A (XSLT scripting deprecated) | - -These use custom diagnostic IDs — suppressing `CS0618` does not suppress them. - -### FilePatternMatch.Stem changed to non-nullable - -`FilePatternMatch.Stem` is now `string` instead of `string?`. Code checking for null may get warnings. - -### Other source-incompatible changes (low impact) - -- `[DynamicallyAccessedMembers]` annotation removed from `DefaultValueAttribute` constructor (affects trimming annotations) -- ARM64 SVE nonfaulting load intrinsics now require a mask parameter - -## Behavioral Changes - -### .NET runtime no longer provides default termination signal handlers - -**Impact: High for console/containerized apps without Generic Host.** - -On Unix, the runtime no longer registers SIGTERM/SIGHUP handlers. On Windows, `CTRL_SHUTDOWN_EVENT` and `CTRL_CLOSE_EVENT` are no longer handled. `AppDomain.ProcessExit` and `AssemblyLoadContext.Unloading` will NOT be raised on termination signals. - -- **ASP.NET Core and Generic Host apps are unaffected** (they register their own handlers) -- **Console apps** must register handlers explicitly: - ```csharp - using var sigterm = PosixSignalRegistration.Create( - PosixSignal.SIGTERM, _ => Environment.Exit(0)); - using var sighup = PosixSignalRegistration.Create( - PosixSignal.SIGHUP, _ => Environment.Exit(0)); - ``` - -### C# 14 overload resolution with span parameters - -Methods with `ReadOnlySpan` or `Span` parameters now participate in type inference and extension method resolution. This can cause `MemoryExtensions.Contains` to bind instead of `Enumerable.Contains` inside Expression lambdas, causing runtime exceptions. - -**Fix:** Cast to `IEnumerable`, use `.AsEnumerable()`, or call the static method explicitly: -```csharp -// Fails — binds to MemoryExtensions.Contains -M((array, num) => array.Contains(num)); -// Fix options: -M((array, num) => ((IEnumerable)array).Contains(num)); -M((array, num) => array.AsEnumerable().Contains(num)); -M((array, num) => Enumerable.Contains(array, num)); -``` - -### BufferedStream.WriteByte no longer performs implicit flush - -`BufferedStream.WriteByte` no longer flushes when the buffer is full. Add explicit `Flush()` calls if your code relied on the implicit behavior. - -### Consistent shift behavior in generic math - -Shift operations in generic math now behave consistently. If custom types relied on the previous inconsistent behavior, update them. - -### Default trace context propagator updated to W3C standard - -The default `DistributedContextPropagator` now uses W3C Trace Context format. If your system relies on legacy propagation formats, configure the propagator explicitly. - -### Other behavioral changes (lower impact) - -- `DriveInfo.DriveFormat` returns actual Linux filesystem type names (e.g., `ext4`) instead of generic values -- `GnuTarEntry`/`PaxTarEntry` no longer include atime/ctime by default — set explicitly if needed -- LDAP `DirectoryControl` parsing is more stringent — invalid data now throws -- MacCatalyst versions normalized differently (affects .NET MAUI) -- `ActivitySource.CreateActivity`/`StartActivity` sampling behavior changed -- `[InlineArray]` structs can no longer have explicit `[StructLayout(Size = ...)]` — assembly fails to load -- `Type.MakeGenericSignatureType` arguments validated more strictly diff --git a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/cryptography-dotnet9to10.md b/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/cryptography-dotnet9to10.md deleted file mode 100644 index ea4c87fa46..0000000000 --- a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/cryptography-dotnet9to10.md +++ /dev/null @@ -1,79 +0,0 @@ -# Cryptography Breaking Changes (.NET 10) - -These changes affect projects using `System.Security.Cryptography`, X.509 certificates, or OpenSSL. - -## Source-Incompatible Changes - -### MLDsa and SlhDsa 'SecretKey' members renamed to 'PrivateKey' - -All members containing `SecretKey` on `MLDsa` and `SlhDsa` types have been renamed to use `PrivateKey`. This affects methods and properties: - -```csharp -// Before -int size = key.Algorithm.SecretKeySizeInBytes; -byte[] output = new byte[size]; -key.ExportMLDsaSecretKey(output); -key.ImportMLDsaSecretKey(data); - -// After -int size = key.Algorithm.PrivateKeySizeInBytes; -byte[] output = new byte[size]; -key.ExportMLDsaPrivateKey(output); -key.ImportMLDsaPrivateKey(data); -// Same pattern for SlhDsa: ExportSlhDsaSecretKey → ExportSlhDsaPrivateKey, etc. -``` - -### Rfc2898DeriveBytes constructors are obsolete (SYSLIB0060) - -All `Rfc2898DeriveBytes` constructors are now obsolete. Use the static `Rfc2898DeriveBytes.Pbkdf2` method instead: - -```csharp -// Before -using var deriveBytes = new Rfc2898DeriveBytes(password, salt, iterations, HashAlgorithmName.SHA256); -byte[] key = deriveBytes.GetBytes(32); - -// After -byte[] key = Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA256, 32); -``` - -### CoseSigner.Key can be null - -`CoseSigner.Key` is now nullable (`AsymmetricAlgorithm?`). Code that assumes it's non-null needs null checks: - -```csharp -// Before -var algorithm = signer.Key.SignatureAlgorithm; - -// After -var algorithm = signer.Key?.SignatureAlgorithm - ?? throw new InvalidOperationException("Key is null"); -``` - -### X509Certificate and PublicKey key parameters can be null - -`X509Certificate.GetKeyAlgorithmParameters()` and `PublicKey.EncodedParameters` can now return null. Add null checks where these values are consumed. - -## Behavioral Changes - -### OpenSSL 1.1.1 or later required on Unix - -.NET 10 requires OpenSSL 1.1.1+ on Unix systems. Older OpenSSL versions are no longer supported. Check with: -```bash -openssl version -``` - -### OpenSSL cryptographic primitives aren't supported on macOS - -Using OpenSSL-specific cryptographic primitives on macOS is no longer supported. Use the platform's native cryptography (Apple Security framework) instead. - -### X500DistinguishedName validation is stricter - -`X500DistinguishedName` now validates input more strictly. Malformed distinguished names that were previously accepted may now throw exceptions. - -### CompositeMLDsa updated to draft-08 - -The Composite ML-DSA implementation has been updated to align with draft-08. Key and signature formats from earlier drafts are incompatible. - -### Environment variable renamed from CLR_OPENSSL_VERSION_OVERRIDE to DOTNET_OPENSSL_VERSION_OVERRIDE - -If you use `CLR_OPENSSL_VERSION_OVERRIDE` to specify the preferred OpenSSL library version on Linux, rename it to `DOTNET_OPENSSL_VERSION_OVERRIDE`. diff --git a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/csharp-compiler-dotnet9to10.md b/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/csharp-compiler-dotnet9to10.md deleted file mode 100644 index caa692a5a5..0000000000 --- a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/csharp-compiler-dotnet9to10.md +++ /dev/null @@ -1,118 +0,0 @@ -# C# 14 Compiler Breaking Changes (.NET 10) - -These breaking changes are introduced by the Roslyn compiler shipping with the .NET 10 SDK. They affect all projects targeting `net10.0` (which uses C# 14 by default). These are maintained separately from the runtime breaking changes at: https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/breaking-changes/compiler%20breaking%20changes%20-%20dotnet%2010 - -## Source-Incompatible Changes - -### `field` keyword in property accessors - -**Impact: High.** `field` is now a contextual keyword inside property `get`, `set`, and `init` accessors (for the semi-auto properties feature). - -Two diagnostics apply: -- **CS9258** (warning, VS 17.12+): `field` binds to the synthesized backing field instead of an existing member (e.g., a class field named `field`). Use `this.field` or `@field` to refer to the member. -- **CS9272** (error, VS 17.14+): A local variable or nested-function parameter named `field` is **disallowed** inside a property accessor. Rename the variable or use `@field`. - -```csharp -// BREAKS — CS9272 error -public object Property -{ - get - { - int field = 0; // error: 'field' is a keyword in a property accessor - return @field; - } -} - -// Also BREAKS — CS9272 error -public string Name -{ - get - { - payload.TryGetProperty("field", out var field); // error: local named 'field' - return field.GetString(); - } -} -``` - -**Fix options:** -1. Rename the variable: `var fieldValue = ...`, `var fieldElem = ...` -2. Escape the identifier: `var @field = ...` (compiles but less readable) -3. For class members named `field`, qualify with `this.field` or `@field` - -### `extension` contextual keyword - -**Impact: Medium.** Starting in C# 14, `extension` is a contextual keyword for extension containers. Code that uses `extension` as a type name, constructor, or return type will break. - -```csharp -// BREAKS in C# 14 -class extension { } // type cannot be named "extension" -using extension = SomeNamespace.Foo; // alias cannot be named "extension" -class C { } // type parameter cannot be named "extension" -``` - -**Fix:** Rename the type, or escape as `@extension`. - -### `Span` and `ReadOnlySpan` overloads applicable in more scenarios - -**Impact: Medium.** C# 14 introduces new built-in span conversions and type inference rules. Different overloads may be chosen, and new ambiguity errors can arise. - -Common patterns affected: -```csharp -// Ambiguity — Assert.Equal(T[], T[]) vs Assert.Equal(ReadOnlySpan, Span) -var x = new long[] { 1 }; -Assert.Equal([2], x); // ambiguous -Assert.Equal([2], x.AsSpan()); // fix - -// Enumerable.Reverse now resolves to MemoryExtensions.Reverse (in-place, returns void) -int[] arr = [1, 2, 3]; -var reversed = arr.Reverse(); // BREAKS: resolves to Span extension, not Enumerable -var reversed = Enumerable.Reverse(arr); // fix - -// ReadOnlySpan preferred over Span — MemoryMarshal.Cast may fail -Span y = MemoryMarshal.Cast(x); // BREAKS -Span y = MemoryMarshal.Cast(x.AsSpan()); // fix - -// ArrayTypeMismatchException with covariant arrays -string[] s = ["a"]; -object[] o = s; -C.R(o); // BREAKS at runtime: Span ctor throws ArrayTypeMismatchException -C.R(o.AsEnumerable()); // fix -``` - -**Fix options:** -- Add `.AsSpan()`, `.AsEnumerable()`, or explicit casts to disambiguate -- Call static methods explicitly (e.g., `Enumerable.Reverse(arr)`) -- API authors: use `[OverloadResolutionPriority]` attribute - -> **Note:** The span overload resolution change is also listed in the runtime breaking changes (`core-libraries.md`). This entry provides the full Roslyn-side detail. - -### Other low-impact source changes - -- **`scoped` in lambda parameters**: Always treated as a modifier. If you have a ref struct type named `scoped`, escape as `@scoped`. -- **`partial` as return type**: Cannot use a type named `partial` as a return type. Escape as `@partial`. - -## Behavioral Changes - -### Enumerator state set to "after" during disposal - -`MoveNext()` on a disposed enumerator now properly returns `false` without executing further user code. Previously, the state machine allowed resuming execution after disposal. - -```csharp -var enumerator = GetItems().GetEnumerator(); -enumerator.MoveNext(); // True, yields 1 -enumerator.Dispose(); -enumerator.MoveNext(); // now returns False (previously could continue) -``` - -### Diagnostics reported for pattern-based disposal in `foreach` - -Obsolete `DisposeAsync` methods on enumerator types are now reported in `await foreach`. Previously these diagnostics were silently ignored. - -### Redundant pattern warning in `or` patterns - -The compiler now warns when the second pattern in a disjunctive `or` is redundant due to precedence: -```csharp -_ = o is not null or 42; // warning: pattern "42" is redundant -_ = o is not int or string; // warning: pattern "string" is redundant -// Likely intended: is not (null or 42) / is not (int or string) -``` diff --git a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/efcore-dotnet9to10.md b/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/efcore-dotnet9to10.md deleted file mode 100644 index 28ed51a1d3..0000000000 --- a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/efcore-dotnet9to10.md +++ /dev/null @@ -1,157 +0,0 @@ -# Entity Framework Core 10 Breaking Changes - -These changes affect projects using EF Core or Microsoft.Data.Sqlite. - -## Medium-Impact Changes - -### EF tools require framework to be specified for multi-targeted projects - -When running EF tools on a project with `` (plural), you must now specify `--framework`: - -```bash -dotnet ef migrations add MyMigration --framework net10.0 -dotnet ef database update --framework net10.0 -``` - -Without this, you'll get: "The project targets multiple frameworks. Use the --framework option to specify which target framework to use." - -## Low-Impact Changes - -### Application Name injected into connection string - -EF now inserts an `Application Name` containing EF and SqlClient version info into connection strings that don't already have one. This changes the effective connection string, which can cause: -- Separate connection pools when mixing EF and non-EF data access (e.g., Dapper) -- Potential distributed transaction escalation within `TransactionScope` -- **Information disclosure**: version strings are visible in `sys.dm_exec_sessions`, database server logs, and monitoring tools, potentially aiding attackers in fingerprinting your stack - -**Mitigation:** Explicitly set `Application Name` in your connection string to a value that does not reveal version information. - -### SQL Server json data type used by default on Azure SQL and compatibility level 170 - -For Azure SQL (`UseAzureSql`) or compatibility level ≥170, EF now maps JSON columns to the `json` data type instead of `nvarchar(max)`. A migration will be generated to alter existing columns. - -**Considerations:** -- SQL Server does not support `DISTINCT` over JSON arrays — queries using it will fail -- The column alteration is a non-trivial schema change - -**Mitigation:** -```csharp -// Option 1: Set compatibility level below 170 -optionsBuilder.UseAzureSql(connStr, o => o.UseCompatibilityLevel(160)); - -// Option 2: Explicitly set column type per property -modelBuilder.Entity() - .PrimitiveCollection(b => b.Tags) - .HasColumnType("nvarchar(max)"); -``` - -### Parameterized collections now use multiple parameters by default - -`.Contains()` on collections now translates to `WHERE x IN (@p1, @p2, @p3)` instead of using `OPENJSON`. This gives the query planner cardinality information but may regress performance for large collections. - -**Mitigation:** -```csharp -// Global: revert to JSON parameter mode -optionsBuilder.UseSqlServer(connStr, - o => o.UseParameterizedCollectionMode(ParameterTranslationMode.Parameter)); - -// Per-query: use EF.Parameter() for JSON array translation -var blogs = await context.Blogs - .Where(b => EF.Parameter(ids).Contains(b.Id)) - .ToListAsync(); -``` - -### ExecuteUpdateAsync now accepts a regular lambda - -`ExecuteUpdateAsync` now takes `Action<...>` instead of `Expression>` for column setters. Code that manually builds expression trees for dynamic setters will no longer compile but can be dramatically simplified: - -```csharp -// Before (.NET 9) — complex expression tree construction for dynamic setters -Expression, SetPropertyCalls>> setters = - s => s.SetProperty(b => b.Views, 8); - -if (nameChanged) -{ - var blogParameter = Expression.Parameter(typeof(Blog), "b"); - setters = Expression.Lambda, SetPropertyCalls>>( - Expression.Call( - instance: setters.Body, - methodName: nameof(SetPropertyCalls.SetProperty), - typeArguments: [typeof(string)], - arguments: - [ - Expression.Lambda>( - Expression.Property(blogParameter, nameof(Blog.Name)), blogParameter), - Expression.Constant("foo") - ]), - setters.Parameters); -} -await context.Blogs.ExecuteUpdateAsync(setters); - -// After (.NET 10) — simple lambda with conditionals -await context.Blogs.ExecuteUpdateAsync(s => -{ - s.SetProperty(b => b.Views, 8); - if (nameChanged) - { - s.SetProperty(b => b.Name, "foo"); - } -}); -``` - -### Complex type column names are now uniquified - -If multiple complex types have properties with the same name, column names are now uniquified by appending a number. This may generate a migration that renames columns. - -**Mitigation:** Explicitly configure column names with `HasColumnName()`. - -### Nested complex type properties use full path in column names - -`EntityType.Complex.NestedComplex.Property` is now mapped to `Complex_NestedComplex_Property` (was `NestedComplex_Property`). This generates a migration renaming columns. - -**Mitigation:** Use `HasColumnName()` to preserve old names. - -### IDiscriminatorPropertySetConvention signature changed - -The method parameter changed from `IConventionEntityTypeBuilder` to `IConventionTypeBaseBuilder`. Update custom convention implementations. - -### IRelationalCommandDiagnosticsLogger methods add logCommandText parameter - -Methods like `CommandReaderExecuting`, `CommandReaderExecuted`, `CommandScalarExecuting`, etc. now have an additional `string logCommandText` parameter containing redacted SQL for logging. Update custom implementations: - -```csharp -public InterceptionResult CommandReaderExecuting( - IRelationalConnection connection, - DbCommand command, - DbContext context, - Guid commandId, - Guid connectionId, - DateTimeOffset startTime, - string logCommandText) // New parameter — redacted SQL for logging -{ - // Use logCommandText for logging (may have constants redacted) - // Use command.CommandText for actual SQL execution -} -``` - -## Microsoft.Data.Sqlite Breaking Changes (All High Impact) - -### GetDateTimeOffset without an offset now assumes UTC - -Previously, a textual timestamp without an offset (e.g., `2014-04-15 10:47:16`) was parsed using the local timezone. Now it's treated as UTC. - -### Writing DateTimeOffset into REAL column now writes in UTC - -`DateTimeOffset` values written to REAL columns are now converted to UTC before writing. Previously the offset was ignored. - -### GetDateTime with an offset now returns value in UTC - -`GetDateTime` on timestamps with offsets (e.g., `2014-04-15 10:47:16+02:00`) now returns the value converted to UTC with `DateTimeKind.Utc`. Previously it returned `DateTimeKind.Local`. - -**Mitigation for all three:** -```csharp -// Temporary workaround to revert to .NET 9 behavior -AppContext.SetSwitch("Microsoft.Data.Sqlite.Pre10TimeZoneHandling", true); -``` - -Review all date/time handling code that reads from or writes to SQLite databases. The new behavior aligns with SQLite's convention that timestamps are UTC. diff --git a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/extensions-hosting-dotnet9to10.md b/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/extensions-hosting-dotnet9to10.md deleted file mode 100644 index 9ef5a011f7..0000000000 --- a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/extensions-hosting-dotnet9to10.md +++ /dev/null @@ -1,75 +0,0 @@ -# Extensions and Hosting Breaking Changes (.NET 10) - -These changes affect projects using `Microsoft.Extensions.Hosting`, `BackgroundService`, `Microsoft.Extensions.Configuration`, and related libraries. - -## Behavioral Changes - -### BackgroundService.ExecuteAsync runs entirely on a background thread - -**Impact: Medium.** Previously, the synchronous code in `ExecuteAsync` before the first `await` ran on the main thread during startup, blocking other hosted services from starting. Now ALL of `ExecuteAsync` runs on a background thread. - -**If startup ordering matters:** - -```csharp -// Option 1: Move synchronous startup code to StartAsync -public override async Task StartAsync(CancellationToken cancellationToken) -{ - // This still runs synchronously during startup - InitializeResources(); - await base.StartAsync(cancellationToken); -} - -// Option 2: Use IHostedLifecycleService for fine-grained lifecycle control -public class MyService : BackgroundService, IHostedLifecycleService -{ - public Task StartingAsync(CancellationToken ct) - { - // runs before StartAsync - return Task.CompletedTask; - } - - public Task StartedAsync(CancellationToken ct) - { - // runs after StartAsync - return Task.CompletedTask; - } - // ... other lifecycle methods -} - -// Option 3: Move code to the constructor -public MyService(ILogger logger) -{ - // Constructor code runs during DI resolution -} -``` - -### Null values preserved in configuration - -**Impact: Medium.** JSON `null` values are now properly bound instead of being converted to empty strings or ignored. **Empty arrays (`[]`) are also now correctly bound as empty arrays instead of being ignored.** - -| Scenario | .NET 9 behavior | .NET 10 behavior | -|----------|----------------|-----------------| -| `"StringProperty": null` | Bound as `""` (empty string) | Bound as `null` (overwrites constructor default) | -| `"IntProperty": null` | Ignored (kept constructor default) | Bound as `null` (if `int?`) | -| `"Array": [null, null]` | Bound as `["", ""]` | Bound as `[null, null]` | -| **`"Array": []`** | **Ignored (`null`)** | **Bound as empty array `[]`** | - -**If you need the old behavior:** -- Replace `null` with `""` in JSON config files -- Or remove `null` entries to skip binding - -### Fix issues in GetKeyedService() and GetKeyedServices() with AnyKey - -`GetKeyedService()` and `GetKeyedServices()` with `AnyKey` now work correctly. If your code relied on the previous buggy behavior, update it. - -### Message no longer duplicated in Console log output - -When using the JSON console logger, messages are no longer duplicated. If your log parsing relied on the duplicated format, update it. - -### ProviderAliasAttribute moved to Microsoft.Extensions.Logging.Abstractions assembly - -`ProviderAliasAttribute` has moved assemblies. If you reference it directly by assembly-qualified name, update the reference. Source-incompatible for code using assembly-qualified type references. - -### Removed DynamicallyAccessedMembers annotation from trim-unsafe configuration code - -The `[DynamicallyAccessedMembers]` annotation was removed from certain configuration APIs that are not trim-safe. Binary incompatible for code that relied on the annotation for trimming analysis. diff --git a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/sdk-msbuild-dotnet9to10.md b/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/sdk-msbuild-dotnet9to10.md deleted file mode 100644 index a962cc67ee..0000000000 --- a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/sdk-msbuild-dotnet9to10.md +++ /dev/null @@ -1,50 +0,0 @@ -# SDK and MSBuild Breaking Changes (.NET 10) - -These changes affect the .NET SDK, CLI tooling, NuGet, and MSBuild behavior. - -## Source-Incompatible Changes - -### NU1510 raised for direct references pruned by NuGet - -If NuGet prunes a direct `PackageReference` because the package is already part of the shared framework, a `NU1510` warning is raised. Remove the explicit reference if it's provided by the framework. - -### PackageReference without a version raises an error - -Every `` must now have a `Version` attribute or use Central Package Management. Missing versions raise an error instead of resolving to the latest. - -### Other source-incompatible changes - -- `dnx.ps1` file removed from .NET SDK — remove any references -- File-level directives (`#r`, `#load`) no longer accept double-quoted paths — remove the quotes (e.g., `#r MyLib.dll` instead of `#r "MyLib.dll"`) -- `project.json` no longer recognized by `dotnet restore` — use `PackageReference` format -- NuGet packages with no runtime assets excluded from `deps.json` -- `ToolCommandName` not set for non-tool packages -- HTTP sources in `dotnet package list`/`dotnet package search` now error (use HTTPS) - -## Behavioral Changes - -### `dotnet new sln` defaults to SLNX file format - -`dotnet new sln` now generates an XML-based `.slnx` file instead of the classic `.sln` format: -```xml - - -``` -**Mitigation:** Use `dotnet new sln --format sln` for the classic format. Ensure your tooling (Visual Studio, Rider, etc.) supports SLNX. - -### Other behavioral changes - -- `--interactive` defaults to `true` in user scenarios — use `--interactive false` in scripts -- CLI diagnostic output now goes to stderr -- Tool packages now include RID-specific content -- Default workload management mode is 'workload sets' (not 'loose manifests') -- `EnableDynamicNativeInstrumentation` defaults to false for code coverage -- `dotnet package list` performs restore before listing -- `dotnet tool install --local` creates manifest by default -- `dotnet watch` logs to stderr instead of stdout -- `PrunePackageReference` privatizes direct prunable references (`PrivateAssets="All"`) -- SHA-1 fingerprints deprecated in `dotnet nuget sign` — use SHA-256 -- `MSBUILDCUSTOMBUILDEVENTWARNING` escape hatch removed -- MSBuild custom culture resource handling changed -- `NUGET_ENABLE_ENHANCED_HTTP_RETRY` env var removed (enhanced retry always on) -- NuGet logs errors for invalid package IDs diff --git a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/serialization-networking-dotnet9to10.md b/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/serialization-networking-dotnet9to10.md deleted file mode 100644 index c6b48cb8b5..0000000000 --- a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/serialization-networking-dotnet9to10.md +++ /dev/null @@ -1,61 +0,0 @@ -# Serialization and Networking Breaking Changes (.NET 10) - -These changes affect projects using System.Text.Json, XmlSerializer, HttpClient, and networking APIs. - -## Serialization - -### System.Text.Json checks for property name conflicts - -**Impact: Medium.** Polymorphic types with properties that conflict with metadata names (`$type`, `$id`, `$ref`, or custom `TypeDiscriminatorPropertyName`) now throw `InvalidOperationException` during serialization instead of producing invalid JSON. - -```csharp -// This now throws InvalidOperationException at serialization time: -[JsonPolymorphic(TypeDiscriminatorPropertyName = "Type")] -[JsonDerivedType(typeof(Dog), "dog")] -public abstract class Animal -{ - public abstract string Type { get; } // Conflicts with "Type" discriminator -} -``` - -**Fix:** rename the conflicting property, or suppress it with `[JsonIgnore]`: - -```csharp -[JsonPolymorphic(TypeDiscriminatorPropertyName = "Type")] -[JsonDerivedType(typeof(Dog), "dog")] -public abstract class Animal -{ - [JsonIgnore] - public abstract string Type { get; } -} -``` - -### XmlSerializer no longer ignores properties marked with ObsoleteAttribute - -**Security consideration:** Properties marked `[Obsolete]` are now included in XML serialization. Previously they were silently skipped. If obsolete properties contain sensitive data (e.g., deprecated password fields, legacy PII, or internal-only values), they will now appear in serialized output. Audit obsolete properties for sensitive data and mark them with `[XmlIgnore]` if they should not be serialized. - -## Networking - -### HTTP/3 support disabled by default with PublishTrimmed - -**When `true` or `true` is set, HTTP/3 support is completely disabled by default.** The HTTP/3 code is stripped by the trimmer. This is NOT a native library search issue — the HTTP/3 implementation code itself is removed. - -**Fix:** Add `true` to your `.csproj` to preserve HTTP/3 support when trimming: -```xml - - true - true - -``` - -### MailAddress enforces validation for consecutive dots - -`MailAddress` now rejects email addresses with consecutive dots (e.g., `user..name@example.com`). Previously these were accepted. - -### Streaming HTTP responses enabled by default in browser HTTP clients - -In Blazor WebAssembly and other browser-based HTTP clients, streaming responses are now enabled by default. This may change how response content is buffered and consumed. - -### Uri length limits removed - -**Security consideration:** The `Uri` class no longer enforces length limits. Previously, very long URIs could throw exceptions. If your application relied on `Uri` to reject excessively long input (as an input validation or sanitization gate), this removal may expose denial-of-service or resource exhaustion attack surface. Add explicit length validation before constructing `Uri` instances from untrusted input. diff --git a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/winforms-wpf-dotnet9to10.md b/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/winforms-wpf-dotnet9to10.md deleted file mode 100644 index 1bdd47812a..0000000000 --- a/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/references/winforms-wpf-dotnet9to10.md +++ /dev/null @@ -1,91 +0,0 @@ -# Windows Forms and WPF Breaking Changes (.NET 10) - -These changes affect projects using Windows Forms (`true`) or WPF (`true`). - -## Windows Forms - -### Source-Incompatible Changes - -#### API obsoletions - -Several Windows Forms APIs have been marked obsolete with custom diagnostic IDs. Follow the guidance in the warning message for each. - -#### Applications referencing both WPF and WinForms must disambiguate MenuItem and ContextMenu types - -If a project references both WPF and WinForms, the `MenuItem` and `ContextMenu` types are ambiguous. Use fully qualified names: - -```csharp -// Before (ambiguous in .NET 10) -var item = new MenuItem("File"); - -// After -var item = new System.Windows.Forms.MenuItem("File"); -// or -var item = new System.Windows.Controls.MenuItem(); -``` - -#### Renamed parameter in HtmlElement.InsertAdjacentElement - -The parameter name in `HtmlElement.InsertAdjacentElement` has changed from `orientation`. Calls that use named arguments with `orientation` will no longer compile; update them to use positional arguments: - -```csharp -// Before — named arguments with old parameter name -element.InsertAdjacentElement(orientation: HtmlElementInsertionOrientation.BeforeBegin, newElement: newElement); - -// After — use positional arguments -element.InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeBegin, newElement); -``` - -### Behavioral Changes - -#### TreeView checkbox image truncation - -The checkbox rendering in `TreeView` controls has been adjusted, which changes text positioning. Visual appearance may differ slightly. - -#### StatusStrip uses System RenderMode by default - -`StatusStrip` now uses the system render mode by default instead of a custom renderer. The visual appearance may change. Set `RenderMode` explicitly to restore the previous look. - -#### System.Drawing OutOfMemoryException changed to ExternalException - -**Important:** Some `System.Drawing` operations that previously threw `OutOfMemoryException` now throw `ExternalException` (from `System.Runtime.InteropServices` — NOT `ArgumentException`). This reflects the actual GDI+ error code. Update catch blocks: - -```csharp -// Before — only catching OutOfMemoryException -try { /* drawing operation */ } -catch (OutOfMemoryException) { /* handle */ } - -// After — catch ExternalException (the new exception type in .NET 10) -try { /* drawing operation */ } -catch (ExternalException) { /* handle */ } -catch (OutOfMemoryException) { /* handle — for older runtimes */ } -``` - -## WPF - -### Source-Incompatible / Behavioral Changes - -#### Empty ColumnDefinitions and RowDefinitions are disallowed - -Empty `` and `` elements in XAML now cause errors. Remove them if they don't contain any definitions: - -```xml - - - - - - - - - - -``` - -#### Incorrect usage of DynamicResource causes application crash - -Incorrect `DynamicResource` usage that was silently ignored now causes crashes at runtime. Common issues: -- Using `DynamicResource` where `StaticResource` is required (e.g., in non-dependency-property contexts) -- Referencing resources that don't exist - -Audit all `DynamicResource` usage in XAML and ensure each reference points to a valid resource and is used in a context that supports dynamic resources. diff --git a/tests/dotnet-blazor/plan-ui-change/eval.yaml b/tests/dotnet-blazor/plan-ui-change/eval.yaml deleted file mode 100644 index 08af2ccb51..0000000000 --- a/tests/dotnet-blazor/plan-ui-change/eval.yaml +++ /dev/null @@ -1,330 +0,0 @@ -name: plan-ui-change -description: Evaluates the dotnet-blazor/plan-ui-change skill -type: capability -config: - timeout: 40m -stimuli: - - name: Project management Kanban board - prompt: | - Build a Blazor page for a project management Kanban board. This is a complex - multi-section layout. Here are the service contracts - already registered in DI: - - ```csharp - public record TaskItem(int Id, string Title, string Assignee, string Priority, DateTime DueDate, string Status); - - public interface ITaskService - { - Task> GetAllTasksAsync(); - Task CreateTaskAsync(string title, string assignee, string priority, DateTime dueDate); - Task UpdateTaskStatusAsync(int taskId, string newStatus); - } - ``` - - The page should have: - - A summary stats bar at the top showing: total task count, count per column (To Do, In Progress, Done), - and a count of overdue tasks (DueDate < today) - - A search bar that filters visible tasks by title (client-side filtering) - - Three columns side by side: "To Do", "In Progress", "Done" - - Each column header shows the column name and the number of tasks in it - - Each column displays task cards showing: title, assignee name, a priority badge (High = red, - Medium = yellow, Low = green CSS class), and the due date formatted as "MMM dd" - - Each task card has "Move Left" and "Move Right" buttons to move the task to the adjacent column - (hide the button if there's no column in that direction). Moving a task calls UpdateTaskStatusAsync - - Each column has an "Add Task" button at the bottom. Clicking it reveals an inline form within that - column with inputs for title, assignee, priority (dropdown: High/Medium/Low), and due date. - A "Save" button calls CreateTaskAsync and a "Cancel" button hides the form - - The page loads all tasks on initialization and handles loading/error states - - Route: `/board` - environment: - commands: - - dotnet new blazor --interactivity Server --no-https - graders: - - type: output-contains - config: - substring: '[Parameter]' - - type: output-contains - config: - substring: EventCallback - - type: output-matches - config: - pattern: (ITaskService|TaskItem) - - type: prompt - rubric: - - The board is organized into focused, reusable components — task cards, columns, and the stats bar are separate from the page itself - - State changes in child components propagate correctly to the parent and other siblings — e.g., moving a task updates the column counts - - Handles loading and error states with conditional rendering (@if/@else) - - name: E-commerce product catalog with filters and pagination - prompt: | - Build a Blazor page for browsing a product catalog. Here are the service contracts - already registered in DI: - - ```csharp - public record Product(int Id, string Name, decimal Price, string Category, double Rating, bool InStock, string ImageUrl); - public record ProductFilter(List? Categories, decimal? MinPrice, decimal? MaxPrice, bool InStockOnly); - public record PagedResult(List Items, int TotalCount, int Page, int PageSize); - - public interface IProductService - { - Task> SearchAsync(ProductFilter filter, string sortBy, int page, int pageSize); - Task> GetCategoriesAsync(); - } - ``` - - The page layout should have: - - A left sidebar (about 25% width) with filter controls: - - Category checkboxes (loaded from GetCategoriesAsync) - - Min price and max price number inputs - - An "In Stock Only" checkbox toggle - - An "Apply Filters" button that triggers a new search - - A "Clear Filters" button that resets all filters to defaults - - A main content area (about 75% width) with: - - A toolbar row containing: a sort dropdown (options: "Price: Low to High", "Price: High to Low", - "Name: A-Z", "Rating: Highest"), and a "Showing X–Y of Z products" label - - A product grid displaying product cards, each showing: a placeholder image div with the product name - as alt text, the product name, the price formatted as currency, a star rating display (e.g., "★★★★☆" - for 4/5), an "Out of Stock" badge if not in stock, and an "Add to Cart" button (disabled when out of stock) - - When a product card is clicked (not the Add to Cart button), the parent should be notified via - EventCallback so it can navigate to a detail page - - Pagination controls at the bottom: "Previous" button (disabled on first page), numbered page buttons, - "Next" button (disabled on last page) - - The page loads the first page of products and the category list on initialization - - Handle loading, empty results, and error states - - Route: `/catalog` - environment: - commands: - - dotnet new blazor --interactivity Server --no-https - graders: - - type: output-contains - config: - substring: '[Parameter]' - - type: output-contains - config: - substring: EventCallback - - type: output-matches - config: - pattern: (IProductService|ProductFilter|PagedResult) - - type: prompt - rubric: - - The catalog uses a multi-component architecture — product cards, filter sidebar, and pagination are separate reusable units - - Child components communicate changes back to the parent via defined interfaces — e.g., filter sidebar notifies the page when filters change, pagination notifies on page change - - Filtering, sorting, and pagination all work together — changing filters resets to page 1, changing sort re-fetches - - Handles loading, empty, and error states with conditional rendering - - name: Multi-step job application wizard - prompt: | - Build a Blazor page for a multi-step job application form. This has many - distinct visual sections and shared state. Here are the service contracts already registered in DI: - - ```csharp - public record JobApplication(PersonalInfo Personal, WorkHistory Work, List References, string CoverLetter); - public record PersonalInfo(string FullName, string Email, string Phone, string Address); - public record WorkHistory(List Entries); - public record WorkEntry(string Company, string Title, DateTime StartDate, DateTime? EndDate, string Description); - public record Reference(string Name, string Relationship, string Email, string Phone); - - public interface IApplicationService - { - Task SubmitApplicationAsync(JobApplication application); - Task ValidateEmailAsync(string email); - } - ``` - - The page should have: - - **Step indicator bar:** - - Shows all steps: "Personal Info" → "Work History" → "References" → "Cover Letter" → "Review & Submit" - - The current step is highlighted, completed steps show a checkmark, future steps are dimmed - - Users can click a completed step to go back and edit it - - **Step 1 — Personal Info:** - - Inputs for full name, email, phone, and address - - Email is validated via ValidateEmailAsync when the user moves to the next step - - A "Next" button that validates required fields before advancing - - **Step 2 — Work History:** - - A dynamic list of work entries — start with one empty entry - - Each entry has: company name, job title, start date, end date (optional, checkbox for "current"), description - - "Add Another Position" button to add more entries - - "Remove" button on each entry (except if it's the only one) - - "Back" and "Next" buttons - - **Step 3 — References:** - - Space for 2-3 references, each with: name, relationship, email, phone - - "Add Reference" button (max 3) - - "Back" and "Next" buttons - - **Step 4 — Cover Letter:** - - A large textarea for the cover letter - - A character count display (e.g., "342 / 2000 characters") - - "Back" and "Next" buttons - - **Step 5 — Review & Submit:** - - Read-only summary of all entered data organized by section - - An "Edit" link next to each section that jumps back to that step - - A "Submit Application" button that calls SubmitApplicationAsync - - After submission, show a confirmation with the application ID - - Route: `/apply` - environment: - commands: - - dotnet new blazor --interactivity Server --no-https - graders: - - type: output-contains - config: - substring: '[Parameter]' - - type: output-contains - config: - substring: EventCallback - - type: output-matches - config: - pattern: (IApplicationService|JobApplication) - - type: prompt - rubric: - - The wizard is decomposed so each step lives in its own component — navigation flows between them rather than toggling visibility in one file - - Step data is passed down via parameters and changes flow up via callbacks — steps don't share or mutate parent state directly - - Navigation between steps validates before advancing — prevents skipping required fields - - The review step displays a read-only summary of all steps and supports going back to edit a specific step - - name: Application settings page with nested tab panels - prompt: | - Build a Blazor page for an application settings dashboard. This has multiple - nested sections. Here are the service contracts - already registered in DI: - - ```csharp - public record UserProfile(string DisplayName, string Email, string AvatarUrl, string Bio); - public record NotificationPrefs(bool EmailNotifications, bool PushNotifications, bool WeeklyDigest, List MutedChannels); - public record SecuritySettings(bool TwoFactorEnabled, DateTime? LastPasswordChange, List Sessions); - public record ActiveSession(string Id, string Device, string Location, DateTime LastActive); - public record AppearanceSettings(string Theme, string FontSize, string Language, bool CompactMode); - - public interface ISettingsService - { - Task GetProfileAsync(); - Task SaveProfileAsync(UserProfile profile); - Task GetNotificationPrefsAsync(); - Task SaveNotificationPrefsAsync(NotificationPrefs prefs); - Task GetSecuritySettingsAsync(); - Task ChangePasswordAsync(string currentPassword, string newPassword); - Task RevokeSessionAsync(string sessionId); - Task GetAppearanceAsync(); - Task SaveAppearanceAsync(AppearanceSettings settings); - } - ``` - - The page should have: - - **Left sidebar navigation (vertical tabs):** - - Four sections: "Profile", "Notifications", "Security", "Appearance" - - The active section is highlighted - - Clicking a section loads its content in the main area - - **Profile section:** - - Editable fields: display name, email, bio (textarea) - - An avatar preview area with the current URL displayed - - A "Save Changes" button — shows a success toast/message on save - - A "Discard Changes" button that reverts to the last saved state - - **Notifications section:** - - Toggle switches for: email notifications, push notifications, weekly digest - - A list of channels with checkboxes to mute/unmute each - - A "Save Preferences" button - - **Security section:** - - A "Change Password" expandable panel with: current password, new password, confirm password fields and a "Update Password" button - - Two-factor authentication toggle with status indicator - - An "Active Sessions" table showing: device, location, last active time, and a "Revoke" button for each session (except the current one) - - A confirmation dialog before revoking a session - - **Appearance section:** - - Theme selector: radio buttons for "Light", "Dark", "System" - - Font size selector: "Small", "Medium", "Large" - - Language dropdown - - Compact mode toggle - - A live preview area that shows how the selected options look - - A "Save" button - - Route: `/settings` - environment: - commands: - - dotnet new blazor --interactivity Server --no-https - graders: - - type: output-contains - config: - substring: '[Parameter]' - - type: output-contains - config: - substring: EventCallback - - type: output-matches - config: - pattern: (ISettingsService|UserProfile|SecuritySettings) - - type: prompt - rubric: - - Each settings section (Profile, Notifications, Security, Appearance) is its own component — not all inlined in the page - - Switching tabs loads the correct section content without a full page reload - - Handles the save/discard flow with appropriate UI feedback (success message, disabled buttons during save) - - name: Team chat interface with message threads - prompt: | - Build a Blazor page for a team messaging app. This is a complex multi-panel - layout with a sidebar, main area, and collapsible thread panel. Here are the service contracts - already registered in DI: - - ```csharp - public record Channel(int Id, string Name, string Description, int UnreadCount); - public record Message(int Id, int ChannelId, string Author, string Content, DateTime SentAt, int? ReplyToId, List Reactions); - public record Reaction(string Emoji, List Users); - public record ThreadSummary(int RootMessageId, int ReplyCount, DateTime LastReplyAt); - - public interface IChatService - { - Task> GetChannelsAsync(); - Task> GetMessagesAsync(int channelId, int skip, int take); - Task SendMessageAsync(int channelId, string content, int? replyToId); - Task> GetThreadAsync(int rootMessageId); - Task AddReactionAsync(int messageId, string emoji); - Task MarkChannelReadAsync(int channelId); - } - ``` - - The page layout should have: - - **Left sidebar (channel list, about 20% width):** - - A list of channels, each showing: channel name (with # prefix), description snippet, and an unread count badge - - The active channel is highlighted - - Clicking a channel loads its messages in the main area and marks it as read - - **Main message area (about 55% width, or 80% if no thread is open):** - - A header showing the current channel name and description - - A scrollable message list showing messages for the selected channel - - Each message displays: author name, timestamp (relative — "2 min ago"), message content, and a row of reaction emoji badges (each showing emoji + count) - - Hovering a message reveals action buttons: "Reply" (opens thread panel), "React" (shows emoji picker with 5-6 common emojis) - - Messages that are thread starters show a "N replies" link below them - - A message input area at the bottom: a textarea and a "Send" button - - Load older messages on scroll-to-top (pagination via skip/take) - - **Right panel (thread view, about 25% width, shown when a thread is open):** - - Header: "Thread" with the original message quoted and a close button - - A scrollable list of reply messages in the thread - - A reply input area at the bottom (textarea + "Reply" button) - - Closing the thread panel widens the main message area back - - Route: `/chat` - environment: - commands: - - dotnet new blazor --interactivity Server --no-https - graders: - - type: output-contains - config: - substring: '[Parameter]' - - type: output-contains - config: - substring: EventCallback - - type: output-matches - config: - pattern: (IChatService|Message|Channel) - - type: prompt - rubric: - - The chat interface is decomposed into focused components — channel list, message area, thread panel, and message input each have clear responsibilities - - The message input component is reused in both the main area and thread panel - - Channel selection, sending messages, and opening threads all work correctly — selecting a channel loads its messages, opening a thread shows replies diff --git a/tests/dotnet-blazor/support-prerendering/eval.yaml b/tests/dotnet-blazor/support-prerendering/eval.yaml deleted file mode 100644 index dcb9022ac2..0000000000 --- a/tests/dotnet-blazor/support-prerendering/eval.yaml +++ /dev/null @@ -1,79 +0,0 @@ -name: support-prerendering -description: Evaluates the dotnet-blazor/support-prerendering skill -type: capability -config: - timeout: 10m -stimuli: - - name: Equipment inventory loaded once - prompt: | - I have an existing Blazor Web App with Interactive Server (per-page). - - I need an interactive /inventory page that shows a table of equipment items - (Id, Name, Location, LastInspected date). The data comes from an EquipmentService - you should create (just return fake data, 5-10 items). - - The page should show "Loading inventory..." until data is ready, then display - the table. The important thing is that when the page first loads I see the HTML - instantly (fast initial paint), but the equipment data should NOT be fetched - twice — once during the initial server render and again when the page becomes - interactive. It should only call the service once and carry that data across. - graders: - - type: file-exists - config: - path: '**/Inventory.razor' - - type: file-contains - config: - path: '**/Inventory.razor' - value: PersistentState - - type: file-contains - config: - path: '**/Inventory.razor' - value: InteractiveServer - - type: file-contains - config: - path: '**/Inventory.razor' - value: '??=' - - type: prompt - rubric: - - Data persists across the prerender-to-interactive handoff — uses state persistence ([PersistentState] or PersistentComponentState) with ??= pattern to avoid duplicate data fetches - - Component correctly shows loading state when data is null, then displays the equipment table when loaded - - Does NOT disable prerendering — preserves the fast initial HTML response while avoiding duplicate loads - - Creates a proper EquipmentService registered in DI, not inline data generation - - name: Notifications page with live polling - prompt: | - I have an existing Blazor Web App with Interactive Server (per-page). - - I need an interactive /notifications page that: - - Loads an initial set of notifications from a NotificationService (create it with fake data) - - After the page becomes interactive, starts a background polling loop that - checks for new notifications every 5 seconds and updates the UI - - Shows a notification count badge and a list of notification messages - - Important constraints: - - The initial notifications should appear in the fast server-rendered HTML - and NOT be fetched again when the page becomes interactive - - The polling loop must not run during the initial server render — only after - the page is live and interactive in the browser - - When the user navigates away, the polling should stop cleanly (no leaked tasks) - graders: - - type: file-exists - config: - path: '**/Notifications.razor' - - type: file-contains - config: - path: '**/Notifications.razor' - value: RendererInfo.IsInteractive - - type: file-contains - config: - path: '**/Notifications.razor' - value: PersistentState - - type: file-contains - config: - path: '**/Notifications.razor' - value: InteractiveServer - - type: prompt - rubric: - - Guards the polling loop so it only runs when the component is interactive — not during prerendering - - Persists initial notification data across the prerender-to-interactive handoff so the service is not called twice - - Polling uses an async loop with CancellationTokenSource, cancelled in DisposeAsync — not System.Threading.Timer - - Component implements IAsyncDisposable and cancels the polling token in DisposeAsync to prevent resource leaks diff --git a/tests/dotnet-diag/android-tombstone-symbolication/crashlog_ios.txt b/tests/dotnet-diag/android-tombstone-symbolication/crashlog_ios.txt deleted file mode 100644 index 6ad106a861..0000000000 --- a/tests/dotnet-diag/android-tombstone-symbolication/crashlog_ios.txt +++ /dev/null @@ -1,41 +0,0 @@ -Incident Identifier: 8A2B3C4D-5E6F-7890-ABCD-EF1234567890 -CrashReporter Key: 1a2b3c4d5e6f7890abcdef1234567890abcdef12 -Hardware Model: iPhone14,5 -Process: MyApp [1234] -Path: /private/var/containers/Bundle/Application/12345678-ABCD-EF01-2345-678901234567/MyApp.app/MyApp -Identifier: com.companyname.MyApp -Version: 1.0 (1) -Code Type: ARM-64 (Native) -Role: Foreground -Parent Process: launchd [1] -Coalition: com.companyname.MyApp [1234] - -Date/Time: 2026-02-25 14:30:22.1234 -0800 -Launch Time: 2026-02-25 14:30:20.5678 -0800 -OS Version: iPhone OS 17.2 (21C62) -Release Type: User -Report Version: 104 - -Exception Type: EXC_CRASH (SIGABRT) -Exception Codes: 0x0000000000000000, 0x0000000000000000 - -Termination Reason: SIGNAL 6 Abort trap: 6 - -Triggered by Thread: 0 - -Thread 0 name: -Thread 0 Crashed: -0 libsystem_kernel.dylib 0x00000001e1234568 __pthread_kill + 8 -1 libsystem_pthread.dylib 0x00000001e2345678 pthread_kill + 288 -2 libsystem_c.dylib 0x00000001e3456789 abort + 180 -3 MyApp 0x0000000100abcdef 0x100000000 + 11259375 -4 MyApp 0x0000000100123456 0x100000000 + 1193046 -5 UIKitCore 0x00000001a1234568 -[UIApplication _run] + 684 -6 UIKitCore 0x00000001a2345679 UIApplicationMain + 340 - -Thread 1: -0 libsystem_kernel.dylib 0x00000001e1234560 __workq_kernreturn + 8 - -Binary Images: -0x100000000 - 0x100ffffff MyApp arm64 <8a2b3c4d5e6f78901234567890abcdef> /private/var/containers/Bundle/Application/12345678-ABCD-EF01-2345-678901234567/MyApp.app/MyApp -0x1e1234000 - 0x1e1238fff libsystem_kernel.dylib arm64e /usr/lib/system/libsystem_kernel.dylib diff --git a/tests/dotnet-diag/android-tombstone-symbolication/eval.yaml b/tests/dotnet-diag/android-tombstone-symbolication/eval.yaml deleted file mode 100644 index 096d039292..0000000000 --- a/tests/dotnet-diag/android-tombstone-symbolication/eval.yaml +++ /dev/null @@ -1,219 +0,0 @@ -name: android-tombstone-symbolication -description: Evaluates the dotnet-diag/android-tombstone-symbolication skill -type: capability -config: - timeout: 5m -stimuli: - - name: Symbolicate .NET frames in an Android tombstone - prompt: I have an Android tombstone file at tombstone_sample.txt from a crashed .NET MAUI app. Please symbolicate the - .NET runtime frames in the backtrace to show function names and source locations. - environment: - files: - - src: . - dest: . - graders: - - type: output-matches - config: - pattern: libmonosgen-2\.0\.so - - type: output-matches - config: - pattern: elf-buildid-sym-1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be - - type: output-matches - config: - pattern: llvm-symbolizer - - type: output-matches - config: - pattern: (0x)?0*222098 - - type: output-matches - config: - pattern: --obj= - - type: output-matches - config: - pattern: msdl\.microsoft\.com - - type: prompt - rubric: - - Identified that the tombstone contains .NET runtime frames from libmonosgen-2.0.so - - Extracted the BuildId 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be from the backtrace - - Constructed the full symbol server URL with the BuildId in the elf-buildid-sym path - - Showed the llvm-symbolizer command with --obj pointing to the debug symbols file and a PC offset from the - tombstone - - Produced or described a symbolicated backtrace with function names and source file locations - - name: Recognize tombstone with no .NET frames - prompt: I have an Android tombstone file at tombstone_no_dotnet.txt from a crashed app. Please symbolicate the .NET - runtime frames. - environment: - files: - - src: . - dest: . - graders: - - type: output-matches - config: - pattern: (no .NET|not a .NET|no .net|no dotnet|no managed|not .NET|does not contain .NET|doesn.t contain .NET|no mono|no - CoreCLR|no libmonosgen|no libcoreclr) - - type: output-matches - config: - pattern: (libc\.so|libart\.so|libutils\.so|libnativeapp\.so) - - type: prompt - rubric: - - Correctly identified that the tombstone contains no .NET runtime libraries (no libmonosgen-2.0.so or - libcoreclr.so) - - Did NOT attempt to download symbols from the Microsoft symbol server - - Did NOT fabricate or hallucinate symbolicated .NET frames - - Mentioned that the crash involves native Android/ART libraries (libc, libart, libutils) rather than .NET - - name: Symbolicate CoreCLR frames in an Android tombstone - prompt: I have an Android tombstone file at tombstone_coreclr.txt from a crashed .NET Android app. Please symbolicate - the .NET runtime frames in the backtrace. - environment: - files: - - src: . - dest: . - graders: - - type: output-matches - config: - pattern: libcoreclr\.so - - type: output-matches - config: - pattern: elf-buildid-sym-4ca7e2f19b3d605847a1c8e3f5b7d9a2c4e6f801 - - type: output-matches - config: - pattern: llvm-symbolizer - - type: output-matches - config: - pattern: (0x)?0*3a81f0 - - type: prompt - rubric: - - Identified that the tombstone contains .NET runtime frames from libcoreclr.so - - Extracted the BuildId 4ca7e2f19b3d605847a1c8e3f5b7d9a2c4e6f801 from the backtrace - - Constructed the full symbol server URL with the BuildId in the elf-buildid-sym path - - Showed the llvm-symbolizer command with --obj and a PC offset from the tombstone - - Did NOT assume the app is Mono-based — correctly identified it as CoreCLR (JIT) - - name: Recognize NativeAOT tombstone with app binary and libSystem.Native.so - prompt: I have an Android tombstone file at tombstone_nativeaot.txt from a crashed .NET Android app compiled with - NativeAOT. Please symbolicate the .NET runtime frames in the backtrace. - environment: - files: - - src: . - dest: . - graders: - - type: output-matches - config: - pattern: (NativeAOT|native.AOT|nativeaot|statically.link|app.binary|libNativeAotApp) - - type: output-matches - config: - pattern: libSystem\.Native\.so - - type: output-matches - config: - pattern: elf-buildid-sym-5e7c2a4b6d8e0f2138b2d4f6a1c3e5079a1b3d5f - - type: prompt - rubric: - - Recognized that this is a NativeAOT app — the runtime is statically linked into the app binary - (libNativeAotApp.so), not a separate libcoreclr.so or libmonosgen-2.0.so - - Identified libSystem.Native.so as a .NET BCL native component that can be symbolicated via the Microsoft symbol - server - - Explained that the app binary (libNativeAotApp.so) requires the app's own debug symbols, not symbols from the - Microsoft symbol server - - Did NOT confuse this with a Mono or CoreCLR JIT app - - name: Symbolicate multi-thread tombstone - prompt: I have an Android tombstone file at tombstone_multithread.txt from a crashed .NET MAUI app. The tombstone - includes backtraces from multiple threads. Please symbolicate all the .NET runtime frames across all threads. - environment: - files: - - src: . - dest: . - graders: - - type: output-matches - config: - pattern: libmonosgen-2\.0\.so - - type: output-matches - config: - pattern: elf-buildid-sym-1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be - - type: output-matches - config: - pattern: (SGen.worker|Finalizer) - - type: output-matches - config: - pattern: (HeapTaskDaemon|SGen.worker|Finalizer) - - type: output-matches - config: - pattern: llvm-symbolizer - - type: prompt - rubric: - - Identified .NET frames from the crashing thread and at least one background thread (SGen worker or Finalizer) - - Recognized that the SGen worker and Finalizer threads also contain libmonosgen-2.0.so frames - - Used the same BuildId to symbolicate frames across all threads (they share the same libmonosgen-2.0.so) - - Showed the llvm-symbolizer command or the automation script for symbolication - - name: Handle .NET frames with no BuildId metadata - prompt: I have an Android tombstone file at tombstone_no_buildid.txt from a crashed .NET app. Please symbolicate the - .NET runtime frames. - environment: - files: - - src: . - dest: . - graders: - - type: output-matches - config: - pattern: libmonosgen-2\.0\.so - - type: output-matches - config: - pattern: (no BuildId|no.build.?id|missing BuildId|without - BuildId|BuildId.*(not|missing|absent|unavailable)|cannot.*(symbolicate|download|resolve)) - - type: prompt - rubric: - - Identified that the tombstone contains .NET runtime frames from libmonosgen-2.0.so - - Recognized that the .NET frames do NOT have BuildId metadata - - Explained that without a BuildId, debug symbols cannot be downloaded from the Microsoft symbol server - - "Suggested alternative approaches: obtaining the unstripped binary from the build, checking NuGet runtime pack, - or local build artifacts" - - Did NOT hallucinate or fabricate a BuildId - - name: Symbolicate tombstone with multiple .NET libraries and different BuildIds - prompt: I have an Android tombstone file at tombstone_multi_buildid.txt from a crashed .NET MAUI app. Please symbolicate - the .NET runtime frames in the backtrace. - environment: - files: - - src: . - dest: . - graders: - - type: output-matches - config: - pattern: libmonosgen-2\.0\.so - - type: output-matches - config: - pattern: libSystem\.Native\.so - - type: output-matches - config: - pattern: elf-buildid-sym-1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be - - type: output-matches - config: - pattern: elf-buildid-sym-7a3b5c9d1e4f6082a3c5d7e9f1b2d4a6c8e0f213 - - type: output-matches - config: - pattern: (elf-buildid-sym-2f4a6b8c|libSystem\.Globalization\.Native\.so) - - type: output-matches - config: - pattern: msdl\.microsoft\.com - - type: prompt - rubric: - - "Identified .NET frames from multiple libraries: libmonosgen-2.0.so, libSystem.Native.so, and - libSystem.Globalization.Native.so" - - Extracted distinct BuildIds for each library and constructed separate symbol server download URLs - - Downloaded (or described downloading) debug symbols for each unique BuildId independently - - Showed the llvm-symbolizer command or automation script for symbolication - - name: Reject iOS crash log as wrong format - prompt: I have a crash log file at crashlog_ios.txt from a crashed app. Please symbolicate the .NET runtime frames. - environment: - files: - - src: . - dest: . - graders: - - type: output-matches - config: - pattern: (iOS|iPhone|Apple|not.*(Android|tombstone)|wrong.*(format|type)|different.*(format|process)) - - type: prompt - rubric: - - Recognized that this is an iOS crash log, not an Android tombstone - - Did NOT attempt to apply the Android tombstone symbolication workflow - - Did NOT attempt to download symbols from the Microsoft ELF symbol server - - Explained that iOS crash logs require a different symbolication process (e.g., atos, dSYMs) - constraints: - reject_skills: - - "*" diff --git a/tests/dotnet-diag/android-tombstone-symbolication/tombstone_coreclr.txt b/tests/dotnet-diag/android-tombstone-symbolication/tombstone_coreclr.txt deleted file mode 100644 index 8dc37915a5..0000000000 --- a/tests/dotnet-diag/android-tombstone-symbolication/tombstone_coreclr.txt +++ /dev/null @@ -1,29 +0,0 @@ -*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** -Build fingerprint: 'google/sdk_gphone64_arm64/emu64a:14/UE1A.230829.036.A2/12269489:userdebug/dev-keys' -Revision: '0' -ABI: 'arm64' -Timestamp: 2026-02-25 21:30:15.742019000+0000 -Process uptime: 2s -Cmdline: com.companyname.CoreClrApp -pid: 9102, tid: 9102, name: .CoreClrApp >>> com.companyname.CoreClrApp <<< -uid: 10188 -tagged_addr_ctrl: 0000000000000001 (PR_TAGGED_ADDR_ENABLE) -signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0000000000000048 - x0 0000000000000000 x1 0000000000000048 x2 0000000000000001 x3 0000000000000000 - x4 0000007483200000 x5 0000000000000010 x6 0000000000000000 x7 7f7f7f7f7f7f7f7f - x8 00000000000000f0 x9 000000749f42a490 x10 0000000000000000 x11 ffffff80ffffffce - x12 0000000000000000 x13 000000000000004f x14 0000000000000000 x15 0000000000000000 - x16 000000749f477a50 x17 000000749f45be1c x18 0000007491b84000 x19 0000000000002396 - x20 0000000000002396 x21 00000000ffffffff x22 000000001476f510 x23 00000074a08c9000 - x24 00000074a0c00e38 x25 00000074a08c9000 x26 0000007491d00000 x27 0000000000000001 - x28 0000000000000000 x29 0000007fe2c51510 - lr 00000074831f4d48 sp 0000007fe2c514e0 pc 00000074831f6e1c pst 0000000000001000 -backtrace: - #00 pc 000000000006ae1c /apex/com.android.runtime/lib64/bionic/libc.so (abort+164) (BuildId: a87908b48b368e6282bcc9f34bcfc28c) - #01 pc 00000000003a81f0 /data/app/~~Qqr987==/com.companyname.CoreClrApp-Stu654==/lib/arm64/libcoreclr.so (BuildId: 4ca7e2f19b3d605847a1c8e3f5b7d9a2c4e6f801) - #02 pc 00000000003a9244 /data/app/~~Qqr987==/com.companyname.CoreClrApp-Stu654==/lib/arm64/libcoreclr.so (BuildId: 4ca7e2f19b3d605847a1c8e3f5b7d9a2c4e6f801) - #03 pc 0000000000298b10 /data/app/~~Qqr987==/com.companyname.CoreClrApp-Stu654==/lib/arm64/libcoreclr.so (BuildId: 4ca7e2f19b3d605847a1c8e3f5b7d9a2c4e6f801) - #04 pc 0000000000298c48 /data/app/~~Qqr987==/com.companyname.CoreClrApp-Stu654==/lib/arm64/libcoreclr.so (BuildId: 4ca7e2f19b3d605847a1c8e3f5b7d9a2c4e6f801) - #05 pc 000000000018e3a4 /data/app/~~Qqr987==/com.companyname.CoreClrApp-Stu654==/lib/arm64/libcoreclr.so (BuildId: 4ca7e2f19b3d605847a1c8e3f5b7d9a2c4e6f801) - #06 pc 000000000018df6c /data/app/~~Qqr987==/com.companyname.CoreClrApp-Stu654==/lib/arm64/libcoreclr.so (BuildId: 4ca7e2f19b3d605847a1c8e3f5b7d9a2c4e6f801) - #07 pc 000000000000307c (BuildId: 0000000000000000000000000000000000000000) diff --git a/tests/dotnet-diag/android-tombstone-symbolication/tombstone_multi_buildid.txt b/tests/dotnet-diag/android-tombstone-symbolication/tombstone_multi_buildid.txt deleted file mode 100644 index 29ba3f91e8..0000000000 --- a/tests/dotnet-diag/android-tombstone-symbolication/tombstone_multi_buildid.txt +++ /dev/null @@ -1,27 +0,0 @@ -*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** -Build fingerprint: 'google/sdk_gphone64_arm64/emu64a:14/UE1A.230829.036.A2/12269489:userdebug/dev-keys' -Revision: '0' -ABI: 'arm64' -Timestamp: 2026-02-25 19:12:33.887412000+0000 -Process uptime: 5s -Cmdline: com.companyname.MultiLibApp -pid: 7820, tid: 7820, name: .MultiLibApp >>> com.companyname.MultiLibApp <<< -uid: 10192 -tagged_addr_ctrl: 0000000000000001 (PR_TAGGED_ADDR_ENABLE) -signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0000000000000000 - x0 0000000000000000 x1 0000000000000010 x2 0000000000000001 x3 0000000000000000 - x4 0000007483200000 x5 0000000000000010 x6 0000000000000000 x7 7f7f7f7f7f7f7f7f - x8 00000000000000f0 x9 000000749f42a490 x10 0000000000000000 x11 ffffff80ffffffce - x16 000000749f477a50 x17 000000749f45be1c x18 0000007491b84000 x19 00000000000018a5 - x20 00000000000018a5 x21 00000000ffffffff x22 000000001476f510 x23 00000074a08c9000 - x28 0000000000000000 x29 0000007fe2c50740 - lr 000000749f42ad48 sp 0000007fe2c50660 pc 000000749f42ce1c pst 0000000000001000 -backtrace: - #00 pc 000000000006ae1c /apex/com.android.runtime/lib64/bionic/libc.so (abort+164) (BuildId: a87908b48b368e6282bcc9f34bcfc28c) - #01 pc 0000000000222098 /data/app/~~Abc123==/com.companyname.MultiLibApp-Def456==/lib/arm64/libmonosgen-2.0.so (BuildId: 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be) - #02 pc 0000000000222234 /data/app/~~Abc123==/com.companyname.MultiLibApp-Def456==/lib/arm64/libmonosgen-2.0.so (BuildId: 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be) - #03 pc 000000000019bac0 /data/app/~~Abc123==/com.companyname.MultiLibApp-Def456==/lib/arm64/libmonosgen-2.0.so (BuildId: 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be) - #04 pc 0000000000008f14 /data/app/~~Abc123==/com.companyname.MultiLibApp-Def456==/lib/arm64/libSystem.Native.so (BuildId: 7a3b5c9d1e4f6082a3c5d7e9f1b2d4a6c8e0f213) - #05 pc 0000000000003b20 /data/app/~~Abc123==/com.companyname.MultiLibApp-Def456==/lib/arm64/libSystem.Globalization.Native.so (BuildId: 2f4a6b8c0d2e4f6a8c0e2f4a6b8c0d2e4f6a8c0e) - #06 pc 000000000019bc14 /data/app/~~Abc123==/com.companyname.MultiLibApp-Def456==/lib/arm64/libmonosgen-2.0.so (BuildId: 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be) - #07 pc 0000000000012a48 /data/app/~~Abc123==/com.companyname.MultiLibApp-Def456==/lib/arm64/libSystem.Native.so (BuildId: 7a3b5c9d1e4f6082a3c5d7e9f1b2d4a6c8e0f213) diff --git a/tests/dotnet-diag/android-tombstone-symbolication/tombstone_multithread.txt b/tests/dotnet-diag/android-tombstone-symbolication/tombstone_multithread.txt deleted file mode 100644 index cf04721f4e..0000000000 --- a/tests/dotnet-diag/android-tombstone-symbolication/tombstone_multithread.txt +++ /dev/null @@ -1,46 +0,0 @@ -*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** -Build fingerprint: 'google/sdk_gphone64_arm64/emu64a:14/UE1A.230829.036.A2/12269489:userdebug/dev-keys' -Revision: '0' -ABI: 'arm64' -Timestamp: 2026-02-25 23:55:20.385027290+0000 -Process uptime: 4s -Cmdline: com.companyname.MauiTest -pid: 7020, tid: 7020, name: uiTest.MauiTest >>> com.companyname.MauiTest <<< -uid: 10156 -tagged_addr_ctrl: 0000000000000001 (PR_TAGGED_ADDR_ENABLE) -signal 6 (SIGABRT), code -1 (SI_QUEUE), fault addr -------- - x0 0000000000000000 x1 0000000000001b6c x2 0000000000000006 x3 0000000000000000 - x8 00000000000000f0 x9 000000749f42a490 x10 0000000000000000 x11 ffffff80ffffffce -backtrace: - #00 pc 000000000006ae1c /apex/com.android.runtime/lib64/bionic/libc.so (abort+164) (BuildId: a87908b48b368e6282bcc9f34bcfc28c) - #01 pc 0000000000222098 /data/app/~~Abc123==/com.companyname.MauiTest-Xyz789==/lib/arm64/libmonosgen-2.0.so (BuildId: 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be) - #02 pc 00000000002241ac /data/app/~~Abc123==/com.companyname.MauiTest-Xyz789==/lib/arm64/libmonosgen-2.0.so (BuildId: 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be) - #03 pc 00000000001abc80 /data/app/~~Abc123==/com.companyname.MauiTest-Xyz789==/lib/arm64/libmonosgen-2.0.so (BuildId: 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be) - #04 pc 000000000016de04 /data/app/~~Abc123==/com.companyname.MauiTest-Xyz789==/lib/arm64/libmonosgen-2.0.so (BuildId: 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be) - #05 pc 000000000000307c (BuildId: 0000000000000000000000000000000000000000) - ---- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- - -pid: 7020, tid: 7027, name: HeapTaskDaemon -backtrace: - #00 pc 00000000000d1e4c /apex/com.android.runtime/lib64/bionic/libc.so (__futex_wait_ex+140) (BuildId: a87908b48b368e6282bcc9f34bcfc28c) - #01 pc 00000000000d5890 /apex/com.android.runtime/lib64/bionic/libc.so (pthread_cond_wait+76) (BuildId: a87908b48b368e6282bcc9f34bcfc28c) - #02 pc 0000000000385a10 /apex/com.android.art/lib64/libart.so (art::ConditionVariable::TimedWait+172) (BuildId: 3a1b9f4e7c2d8056a3b1c9f4e7d2a058) - #03 pc 000000000048c2e8 /apex/com.android.art/lib64/libart.so (art::gc::TaskProcessor::GetTask+120) (BuildId: 3a1b9f4e7c2d8056a3b1c9f4e7d2a058) - ---- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- - -pid: 7020, tid: 7046, name: SGen worker -backtrace: - #00 pc 00000000000d1e4c /apex/com.android.runtime/lib64/bionic/libc.so (__futex_wait_ex+140) (BuildId: a87908b48b368e6282bcc9f34bcfc28c) - #01 pc 00000000000d5890 /apex/com.android.runtime/lib64/bionic/libc.so (pthread_cond_wait+76) (BuildId: a87908b48b368e6282bcc9f34bcfc28c) - #02 pc 00000000002f4b20 /data/app/~~Abc123==/com.companyname.MauiTest-Xyz789==/lib/arm64/libmonosgen-2.0.so (BuildId: 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be) - #03 pc 00000000002f4c84 /data/app/~~Abc123==/com.companyname.MauiTest-Xyz789==/lib/arm64/libmonosgen-2.0.so (BuildId: 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be) - ---- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- - -pid: 7020, tid: 7048, name: Finalizer -backtrace: - #00 pc 00000000000d1e4c /apex/com.android.runtime/lib64/bionic/libc.so (__futex_wait_ex+140) (BuildId: a87908b48b368e6282bcc9f34bcfc28c) - #01 pc 00000000000d5c14 /apex/com.android.runtime/lib64/bionic/libc.so (sem_wait+28) (BuildId: a87908b48b368e6282bcc9f34bcfc28c) - #02 pc 00000000002c1a40 /data/app/~~Abc123==/com.companyname.MauiTest-Xyz789==/lib/arm64/libmonosgen-2.0.so (BuildId: 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be) diff --git a/tests/dotnet-diag/android-tombstone-symbolication/tombstone_nativeaot.txt b/tests/dotnet-diag/android-tombstone-symbolication/tombstone_nativeaot.txt deleted file mode 100644 index 89766a1591..0000000000 --- a/tests/dotnet-diag/android-tombstone-symbolication/tombstone_nativeaot.txt +++ /dev/null @@ -1,26 +0,0 @@ -*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** -Build fingerprint: 'google/sdk_gphone64_arm64/emu64a:14/UE1A.230829.036.A2/12269489:userdebug/dev-keys' -Revision: '0' -ABI: 'arm64' -Timestamp: 2026-02-25 22:45:10.318274000+0000 -Process uptime: 1s -Cmdline: com.companyname.NativeAotApp -pid: 9503, tid: 9503, name: .NativeAotApp >>> com.companyname.NativeAotApp <<< -uid: 10195 -tagged_addr_ctrl: 0000000000000001 (PR_TAGGED_ADDR_ENABLE) -signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0000000000000000 - x0 0000000000000000 x1 0000000000000010 x2 0000000000000001 x3 0000000000000000 - x4 0000007483200000 x5 0000000000000010 x6 0000000000000000 x7 7f7f7f7f7f7f7f7f - x8 00000000000000f0 x9 000000749f42a490 x10 0000000000000000 x11 ffffff80ffffffce - x16 000000749f477a50 x17 000000749f45be1c x18 0000007491b84000 x19 0000000000002501 - x20 0000000000002501 x21 00000000ffffffff x22 000000001476f510 x23 00000074a08c9000 - x28 0000000000000000 x29 0000007fe2c51510 - lr 00000074831f4d48 sp 0000007fe2c514e0 pc 00000074831f6e1c pst 0000000000001000 -backtrace: - #00 pc 000000000006ae1c /apex/com.android.runtime/lib64/bionic/libc.so (abort+164) (BuildId: a87908b48b368e6282bcc9f34bcfc28c) - #01 pc 0000000000415a20 /data/app/~~Lmn321==/com.companyname.NativeAotApp-Opq654==/lib/arm64/libNativeAotApp.so (BuildId: 8b2d4f6a1c3e5078a9b1d3f5e7c2a4b6d8e0f213) - #02 pc 0000000000415b84 /data/app/~~Lmn321==/com.companyname.NativeAotApp-Opq654==/lib/arm64/libNativeAotApp.so (BuildId: 8b2d4f6a1c3e5078a9b1d3f5e7c2a4b6d8e0f213) - #03 pc 000000000038c1f0 /data/app/~~Lmn321==/com.companyname.NativeAotApp-Opq654==/lib/arm64/libNativeAotApp.so (BuildId: 8b2d4f6a1c3e5078a9b1d3f5e7c2a4b6d8e0f213) - #04 pc 000000000038c344 /data/app/~~Lmn321==/com.companyname.NativeAotApp-Opq654==/lib/arm64/libNativeAotApp.so (BuildId: 8b2d4f6a1c3e5078a9b1d3f5e7c2a4b6d8e0f213) - #05 pc 0000000000012a48 /data/app/~~Lmn321==/com.companyname.NativeAotApp-Opq654==/lib/arm64/libSystem.Native.so (BuildId: 5e7c2a4b6d8e0f2138b2d4f6a1c3e5079a1b3d5f) - #06 pc 000000000000307c (BuildId: 0000000000000000000000000000000000000000) diff --git a/tests/dotnet-diag/android-tombstone-symbolication/tombstone_no_buildid.txt b/tests/dotnet-diag/android-tombstone-symbolication/tombstone_no_buildid.txt deleted file mode 100644 index d328f89500..0000000000 --- a/tests/dotnet-diag/android-tombstone-symbolication/tombstone_no_buildid.txt +++ /dev/null @@ -1,25 +0,0 @@ -*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** -Build fingerprint: 'google/sdk_gphone64_arm64/emu64a:14/UE1A.230829.036.A2/12269489:userdebug/dev-keys' -Revision: '0' -ABI: 'arm64' -Timestamp: 2026-02-25 18:30:44.112348000+0000 -Process uptime: 3s -Cmdline: com.companyname.NoBuildIdApp -pid: 6301, tid: 6301, name: .NoBuildIdApp >>> com.companyname.NoBuildIdApp <<< -uid: 10187 -tagged_addr_ctrl: 0000000000000001 (PR_TAGGED_ADDR_ENABLE) -signal 6 (SIGABRT), code -1 (SI_QUEUE), fault addr -------- - x0 0000000000000000 x1 00000000000018a5 x2 0000000000000006 x3 0000007fe3c50670 - x4 0000000000000000 x5 0000000000000000 x6 0000000000000000 x7 7f7f7f7f7f7f7f7f - x8 00000000000000f0 x9 0000007495a06490 x10 0000000000000000 x11 ffffff80ffffffce - x16 0000007495a53a50 x17 0000007495a37e1c x18 00000074937a0000 x19 00000000000018a5 - x20 00000000000018a5 x21 00000000ffffffff x22 000000001476f510 x23 00000074a08c9000 - x28 0000000000000000 x29 0000007fe3c50740 - lr 0000007495a06d48 sp 0000007fe3c50660 pc 0000007495a08e1c pst 0000000000001000 -backtrace: - #00 pc 000000000006ae1c /apex/com.android.runtime/lib64/bionic/libc.so (abort+164) (BuildId: a87908b48b368e6282bcc9f34bcfc28c) - #01 pc 0000000000222098 /data/app/~~Abc123==/com.companyname.NoBuildIdApp-Def456==/lib/arm64/libmonosgen-2.0.so - #02 pc 0000000000222234 /data/app/~~Abc123==/com.companyname.NoBuildIdApp-Def456==/lib/arm64/libmonosgen-2.0.so - #03 pc 000000000019bac0 /data/app/~~Abc123==/com.companyname.NoBuildIdApp-Def456==/lib/arm64/libmonosgen-2.0.so - #04 pc 000000000019bc14 /data/app/~~Abc123==/com.companyname.NoBuildIdApp-Def456==/lib/arm64/libmonosgen-2.0.so - #05 pc 0000000000012a48 /data/app/~~Abc123==/com.companyname.NoBuildIdApp-Def456==/lib/arm64/libSystem.Native.so diff --git a/tests/dotnet-diag/android-tombstone-symbolication/tombstone_no_dotnet.txt b/tests/dotnet-diag/android-tombstone-symbolication/tombstone_no_dotnet.txt deleted file mode 100644 index 0d75925f0e..0000000000 --- a/tests/dotnet-diag/android-tombstone-symbolication/tombstone_no_dotnet.txt +++ /dev/null @@ -1,20 +0,0 @@ -*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** -Build fingerprint: 'google/sdk_gphone64_arm64/emu64a:14/UE1A.230829.036.A2/12269489:userdebug/dev-keys' -Revision: '0' -ABI: 'arm64' -Timestamp: 2026-02-25 19:12:44.102938000+0000 -Process uptime: 3s -Cmdline: com.example.nativeapp -pid: 8401, tid: 8401, name: ple.nativeapp >>> com.example.nativeapp <<< -uid: 10201 -tagged_addr_ctrl: 0000000000000001 (PR_TAGGED_ADDR_ENABLE) -signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0000000000000000 - x0 0000000000000000 x1 0000000000000010 x2 0000000000000001 x3 0000000000000000 - x8 00000000000000f0 x9 000000749f42a490 x10 0000000000000000 x11 ffffff80ffffffce -backtrace: - #00 pc 000000000004a1b0 /apex/com.android.runtime/lib64/bionic/libc.so (strlen+16) (BuildId: a87908b48b368e6282bcc9f34bcfc28c) - #01 pc 0000000000032f44 /system/lib64/libutils.so (android::String8::set+20) (BuildId: 7e3b91c4f2a8d5e1b3c7a9f0d2e4b6a8) - #02 pc 000000000001a8bc /data/app/~~Def456==/com.example.nativeapp-Ghi012==/lib/arm64/libnativeapp.so (Java_com_example_NativeLib_processData+124) (BuildId: f4c2a1b8e7d3096542f1a8c3b5e7d9f2a1b4c6e8) - #03 pc 0000000000215a40 /apex/com.android.art/lib64/libart.so (art_quick_generic_jni_trampoline+144) (BuildId: 3a1b9f4e7c2d8056a3b1c9f4e7d2a058) - #04 pc 000000000020c3a8 /apex/com.android.art/lib64/libart.so (art_quick_invoke_stub+568) (BuildId: 3a1b9f4e7c2d8056a3b1c9f4e7d2a058) - #05 pc 00000000002a14dc /apex/com.android.art/lib64/libart.so (art::interpreter::Execute+292) (BuildId: 3a1b9f4e7c2d8056a3b1c9f4e7d2a058) diff --git a/tests/dotnet-diag/android-tombstone-symbolication/tombstone_sample.txt b/tests/dotnet-diag/android-tombstone-symbolication/tombstone_sample.txt deleted file mode 100644 index bb7fea1318..0000000000 --- a/tests/dotnet-diag/android-tombstone-symbolication/tombstone_sample.txt +++ /dev/null @@ -1,38 +0,0 @@ -*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** -Build fingerprint: 'google/sdk_gphone64_arm64/emu64a:14/UE1A.230829.036.A2/12269489:userdebug/dev-keys' -Revision: '0' -ABI: 'arm64' -Timestamp: 2026-02-25 23:55:20.385027290+0000 -Process uptime: 1s -Cmdline: com.companyname.MauiTest -pid: 7020, tid: 7020, name: uiTest.MauiTest >>> com.companyname.MauiTest <<< -uid: 10156 -tagged_addr_ctrl: 0000000000000001 (PR_TAGGED_ADDR_ENABLE) -signal 6 (SIGABRT), code -1 (SI_QUEUE), fault addr -------- -Abort message: 'not combatible' - x0 0000000000000000 x1 0000000000001b6c x2 0000000000000006 x3 0000000000000000 - x4 464e472b47282b15 x5 464e472b47282b15 x6 464e472b47282b15 x7 7f7f7f7f7f7f7f7f - x8 00000000000000f0 x9 000000749f42a490 x10 0000000000000000 x11 ffffff80ffffffce - x12 0000000000000000 x13 000000000000004f x14 0070006f00200073 x15 00740072006f0062 - x16 000000749f477a50 x17 000000749f45be1c x18 0000007491b84000 x19 0000000000001b6c - x20 0000000000001b6c x21 00000000ffffffff x22 000000001476f510 x23 00000074a08c9000 - x24 00000074a0c00e38 x25 00000074a08c9000 x26 0000007491d00000 x27 0000000000000001 - x28 0000000000000000 x29 0000007fe2c51510 - lr 000000749f460d48 sp 0000007fe2c514e0 pc 000000749f462e1c pst 0000000000001000 -backtrace: - #00 pc 000000000006ae1c /apex/com.android.runtime/lib64/bionic/libc.so (abort+164) (BuildId: a87908b48b368e6282bcc9f34bcfc28c) - #01 pc 0000000000222098 /data/app/~~Abc123==/com.companyname.MauiTest-Xyz789==/lib/arm64/libmonosgen-2.0.so (BuildId: 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be) - #02 pc 00000000002241ac /data/app/~~Abc123==/com.companyname.MauiTest-Xyz789==/lib/arm64/libmonosgen-2.0.so (BuildId: 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be) - #03 pc 00000000001abc80 /data/app/~~Abc123==/com.companyname.MauiTest-Xyz789==/lib/arm64/libmonosgen-2.0.so (BuildId: 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be) - #04 pc 00000000001abd14 /data/app/~~Abc123==/com.companyname.MauiTest-Xyz789==/lib/arm64/libmonosgen-2.0.so (BuildId: 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be) - #05 pc 000000000016dfa4 /data/app/~~Abc123==/com.companyname.MauiTest-Xyz789==/lib/arm64/libmonosgen-2.0.so (BuildId: 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be) - #06 pc 000000000016db6c /data/app/~~Abc123==/com.companyname.MauiTest-Xyz789==/lib/arm64/libmonosgen-2.0.so (BuildId: 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be) - #07 pc 000000000016de04 /data/app/~~Abc123==/com.companyname.MauiTest-Xyz789==/lib/arm64/libmonosgen-2.0.so (BuildId: 1eb39fc72918c7c6c0c610b79eb3d3d47b2f81be) - #08 pc 000000000000307c (BuildId: 0000000000000000000000000000000000000000) - -memory near x14 (interpreted as UTF-16): - 0070006f00200073 's o m e i n t' - 006e006500740072 'e n t i o n a l' - 006100200020006c ' c r a s h o' - 0074007200610020 'n s t a r t u' - 002e00700075006c 'p . ' diff --git a/tests/dotnet-diag/microbenchmarking/TextAnalyzer/TextAnalyzer.cs b/tests/dotnet-diag/microbenchmarking/TextAnalyzer/TextAnalyzer.cs deleted file mode 100644 index bb04ae169c..0000000000 --- a/tests/dotnet-diag/microbenchmarking/TextAnalyzer/TextAnalyzer.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; - -namespace TextAnalysis; - -/// -/// Analyzes text content and provides statistical summaries. -/// Pre-computes word metrics on construction for efficient repeated queries. -/// -public class TextAnalyzer -{ - private readonly string[] _words; - private readonly ReadOnlyCollection _wordLengths; - - public TextAnalyzer(string text) - { - ArgumentNullException.ThrowIfNull(text); - _words = text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); - - int[] lengths = new int[_words.Length]; - for (int i = 0; i < _words.Length; i++) - lengths[i] = _words[i].Length; - _wordLengths = new ReadOnlyCollection(lengths); - } - - /// Gets the number of words in the text. - public int WordCount => _words.Length; - - /// Computes the average word length. - public double AverageWordLength() - { - if (_wordLengths.Count == 0) return 0; - int total = 0; - for (int i = 0; i < _wordLengths.Count; i++) - total += _wordLengths[i]; - return (double)total / _wordLengths.Count; - } - - /// - /// Builds a histogram of word lengths. Index i contains the count - /// of words with length i. - /// - public ReadOnlyCollection WordLengthHistogram() - { - int max = 0; - for (int i = 0; i < _wordLengths.Count; i++) - if (_wordLengths[i] > max) max = _wordLengths[i]; - if (max == 0) return new ReadOnlyCollection([]); - int[] histogram = new int[max + 1]; - for (int i = 0; i < _wordLengths.Count; i++) - histogram[_wordLengths[i]]++; - return new ReadOnlyCollection(histogram); - } - - /// Counts the number of unique words (case-insensitive). - public int UniqueWordCount() - { - var seen = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (string word in _words) - seen.Add(word); - return seen.Count; - } -} diff --git a/tests/dotnet-diag/microbenchmarking/TextAnalyzer/TextAnalyzer.csproj b/tests/dotnet-diag/microbenchmarking/TextAnalyzer/TextAnalyzer.csproj deleted file mode 100644 index 77e0728a0e..0000000000 --- a/tests/dotnet-diag/microbenchmarking/TextAnalyzer/TextAnalyzer.csproj +++ /dev/null @@ -1,7 +0,0 @@ - - - net9.0 - enable - enable - - diff --git a/tests/dotnet-diag/microbenchmarking/eval.yaml b/tests/dotnet-diag/microbenchmarking/eval.yaml deleted file mode 100644 index 89af6f129d..0000000000 --- a/tests/dotnet-diag/microbenchmarking/eval.yaml +++ /dev/null @@ -1,38 +0,0 @@ -name: microbenchmarking -description: Evaluates the dotnet-diag/microbenchmarking skill -type: capability -config: - timeout: 10m -stimuli: - - name: Investigate runtime upgrade performance impact - prompt: > - Your team is upgrading the codebase from .NET 9 to .NET 10. You have been asked to benchmark AverageWordLength, - WordLengthHistogram, and UniqueWordCount to check how the upgrade will impact their performance. The source code - is in the TextAnalyzer subdirectory (TextAnalyzer.cs and TextAnalyzer.csproj). We don't need anything too - comprehensive, don't spend more than 10 minutes on this. Don't worry about cleaning up any files or projects you - create along the way. Note: this machine may be under load from other processes. If the .NET 9 runtime is missing, - install it using the official dotnet-install script from https://dot.net/v1/dotnet-install.sh (or - dotnet-install.ps1 on Windows). - environment: - files: - - src: . - dest: . - graders: - - type: file-contains - config: - path: "**/*.csproj" - value: BenchmarkDotNet - - type: file-exists - config: - path: "**/*-report*.md" - - type: prompt - rubric: - - "The benchmarks follow best practices: methods return their results to prevent dead code elimination, input data - is stored in fields/properties rather than const or literal values, and initialization/data setup is in a setup - method not inside the benchmark methods" - - The agent let NuGet resolve the BenchmarkDotNet version rather than writing one from memory - - The benchmarks were actually run and completed, producing results that compare .NET 9 vs .NET 10 - - The agent correctly identified that AverageWordLength and WordLengthHistogram got significantly faster on .NET - 10 (expected ~2-3x faster), while UniqueWordCount showed no meaningful change - - The agent completed the task efficiently within the time constraints rather than spending excessive time on - unnecessary iterations or troubleshooting diff --git a/tests/dotnet-maui/maui-collectionview/eval.yaml b/tests/dotnet-maui/maui-collectionview/eval.yaml deleted file mode 100644 index dfa4c9518e..0000000000 --- a/tests/dotnet-maui/maui-collectionview/eval.yaml +++ /dev/null @@ -1,129 +0,0 @@ -name: maui-collectionview -description: Evaluates the dotnet-maui/maui-collectionview skill -type: capability -config: - timeout: 2m -stimuli: - - name: Basic CollectionView with data binding and DataTemplate - prompt: | - I have an ObservableCollection with Name and Price properties. - Show me how to display these products in a vertical scrollable list using - CollectionView with a DataTemplate that shows both the name and price. - Use compiled bindings. - graders: - - type: output-contains - config: - substring: CollectionView - - type: output-contains - config: - substring: ItemsSource - - type: output-contains - config: - substring: DataTemplate - - type: output-contains - config: - substring: x:DataType - - type: output-contains - config: - substring: ObservableCollection - - type: prompt - rubric: - - Uses CollectionView with ItemsSource bound to the collection - - Defines a DataTemplate with x:DataType for compiled bindings - - Binds both Name and Price properties inside the template - - Does NOT use ViewCell as the template root - - Uses ObservableCollection rather than List - - name: Grid layout with CollectionView - prompt: | - I want to display a photo gallery using CollectionView in a 3-column - grid layout with spacing between items. Each item should show an image - and a caption. How do I set this up in XAML? - graders: - - type: output-contains - config: - substring: GridItemsLayout - - type: output-contains - config: - substring: Span - - type: output-contains - config: - substring: CollectionView - - type: output-matches - config: - pattern: (?i)spacing|ItemSpacing - - type: prompt - rubric: - - Uses GridItemsLayout with Orientation and Span="3" - - Configures spacing via VerticalItemSpacing and HorizontalItemSpacing - - Includes a DataTemplate with Image and Label for caption - - Does NOT use ViewCell - - name: Selection and pull-to-refresh with CollectionView - prompt: | - I need a CollectionView that supports single item selection and - pull-to-refresh. When the user selects an item, I want to navigate - to a detail page. When they pull to refresh, I want to reload data - from my API. Show me the XAML and explain the ViewModel bindings needed. - graders: - - type: output-contains - config: - substring: SelectionMode - - type: output-contains - config: - substring: SelectedItem - - type: output-contains - config: - substring: RefreshView - - type: output-contains - config: - substring: IsRefreshing - - type: prompt - rubric: - - Sets SelectionMode to Single and binds SelectedItem with TwoWay binding - - Wraps CollectionView in a RefreshView with IsRefreshing and Command bindings - - Explains that IsRefreshing must be set back to false when refresh completes - - Uses SelectionChangedCommand or SelectedItem binding for navigation - - name: Avoid ListView and ViewCell mistakes - prompt: | - I'm migrating from Xamarin.Forms to .NET MAUI. My existing code uses - ListView with ViewCell for each item. Should I keep using ListView in - MAUI? Also, can I reuse my ViewCell templates inside CollectionView? - graders: - - type: output-contains - config: - substring: CollectionView - - type: output-matches - config: - pattern: (?i)(not|never|don.t|avoid|remove|replace).{0,40}ViewCell|ViewCell.{0,40}(not|never|don.t|avoid|remove|replace) - - type: prompt - rubric: - - Recommends migrating from ListView to CollectionView - - Explains that CollectionView has better performance than ListView - - Clearly states that ViewCell must NOT be used with CollectionView - - Suggests using Grid, StackLayout, or other View/Layout as the template root instead of ViewCell - - name: ItemSizingStrategy placement for uniform items - prompt: | - My CollectionView scrolls slowly. Every row is exactly the same height — - a 44px avatar and a single line of text. I read that measuring every item - is the bottleneck. Show me the XAML to switch to measuring only the first - item, and tell me when that would be the wrong choice. - graders: - - type: output-contains - config: - substring: ItemSizingStrategy - - type: output-contains - config: - substring: MeasureFirstItem - # Regression guard: ItemSizingStrategy is declared on StructuredItemsView, - # so it must be set on . Setting it on LinearItemsLayout or - # GridItemsLayout is a hard build break: - # error MAUIX2002: No accessible property, BindableProperty, or event - # found for "ItemSizingStrategy" - - type: output-not-matches - config: - pattern: <(Linear|Grid)ItemsLayout[^>]*ItemSizingStrategy - - type: prompt - rubric: - - Sets ItemSizingStrategy="MeasureFirstItem" on the CollectionView element itself - - Does NOT set ItemSizingStrategy on LinearItemsLayout or GridItemsLayout, which does not compile - - Explains that MeasureFirstItem is only safe when every item is the same size - - Warns that variable-height items will be clipped or stretched, and that MeasureAllItems is the default diff --git a/tests/dotnet-msbuild/check-bin-obj-clash/.gitignore b/tests/dotnet-msbuild/check-bin-obj-clash/.gitignore deleted file mode 100644 index ce59cf64f9..0000000000 --- a/tests/dotnet-msbuild/check-bin-obj-clash/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# Build artifacts from SharedObj/SharedOutput clash demo -SharedObj/ -SharedOutput/ diff --git a/tests/dotnet-msbuild/check-bin-obj-clash/ClashTest.slnx b/tests/dotnet-msbuild/check-bin-obj-clash/ClashTest.slnx deleted file mode 100644 index 14351c7db7..0000000000 --- a/tests/dotnet-msbuild/check-bin-obj-clash/ClashTest.slnx +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/tests/dotnet-msbuild/check-bin-obj-clash/ConsumerApp/Consumer.cs b/tests/dotnet-msbuild/check-bin-obj-clash/ConsumerApp/Consumer.cs deleted file mode 100644 index b80e857e58..0000000000 --- a/tests/dotnet-msbuild/check-bin-obj-clash/ConsumerApp/Consumer.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace ConsumerApp; - -public class Consumer -{ - public string Describe() => new ToolLib.Tool().GetName(); -} diff --git a/tests/dotnet-msbuild/check-bin-obj-clash/ConsumerApp/ConsumerApp.csproj b/tests/dotnet-msbuild/check-bin-obj-clash/ConsumerApp/ConsumerApp.csproj deleted file mode 100644 index 3c315275cb..0000000000 --- a/tests/dotnet-msbuild/check-bin-obj-clash/ConsumerApp/ConsumerApp.csproj +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - net8.0 - enable - enable - - - - - - - - - - diff --git a/tests/dotnet-msbuild/check-bin-obj-clash/LibraryA/ClassA.cs b/tests/dotnet-msbuild/check-bin-obj-clash/LibraryA/ClassA.cs deleted file mode 100644 index 91d7881a65..0000000000 --- a/tests/dotnet-msbuild/check-bin-obj-clash/LibraryA/ClassA.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace LibraryA; - -public class ClassA -{ - public string GetName() => "LibraryA"; -} diff --git a/tests/dotnet-msbuild/check-bin-obj-clash/LibraryA/LibraryA.csproj b/tests/dotnet-msbuild/check-bin-obj-clash/LibraryA/LibraryA.csproj deleted file mode 100644 index 957e2ea088..0000000000 --- a/tests/dotnet-msbuild/check-bin-obj-clash/LibraryA/LibraryA.csproj +++ /dev/null @@ -1,22 +0,0 @@ - - - - ..\SharedOutput\ - $(BaseOutputPath)$(Configuration)\ - ..\SharedObj\ - $(BaseIntermediateOutputPath)$(Configuration)\ - false - false - - - - - - net8.0 - enable - enable - - - - - diff --git a/tests/dotnet-msbuild/check-bin-obj-clash/LibraryB/ClassB.cs b/tests/dotnet-msbuild/check-bin-obj-clash/LibraryB/ClassB.cs deleted file mode 100644 index 7dac2d24ae..0000000000 --- a/tests/dotnet-msbuild/check-bin-obj-clash/LibraryB/ClassB.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace LibraryB; - -public class ClassB -{ - public string GetName() => "LibraryB"; -} diff --git a/tests/dotnet-msbuild/check-bin-obj-clash/LibraryB/LibraryB.csproj b/tests/dotnet-msbuild/check-bin-obj-clash/LibraryB/LibraryB.csproj deleted file mode 100644 index 957e2ea088..0000000000 --- a/tests/dotnet-msbuild/check-bin-obj-clash/LibraryB/LibraryB.csproj +++ /dev/null @@ -1,22 +0,0 @@ - - - - ..\SharedOutput\ - $(BaseOutputPath)$(Configuration)\ - ..\SharedObj\ - $(BaseIntermediateOutputPath)$(Configuration)\ - false - false - - - - - - net8.0 - enable - enable - - - - - diff --git a/tests/dotnet-msbuild/check-bin-obj-clash/MultiTargetLib/MultiClass.cs b/tests/dotnet-msbuild/check-bin-obj-clash/MultiTargetLib/MultiClass.cs deleted file mode 100644 index 16051debc2..0000000000 --- a/tests/dotnet-msbuild/check-bin-obj-clash/MultiTargetLib/MultiClass.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace MultiTargetLib; - -public class MultiClass -{ - public string GetFramework() => -#if NET8_0 - "net8.0"; -#elif NET9_0 - "net9.0"; -#else - "unknown"; -#endif -} diff --git a/tests/dotnet-msbuild/check-bin-obj-clash/MultiTargetLib/MultiTargetLib.csproj b/tests/dotnet-msbuild/check-bin-obj-clash/MultiTargetLib/MultiTargetLib.csproj deleted file mode 100644 index 1c0ffb7409..0000000000 --- a/tests/dotnet-msbuild/check-bin-obj-clash/MultiTargetLib/MultiTargetLib.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - false - false - - - - - - - net8.0;net9.0 - enable - enable - - - - - diff --git a/tests/dotnet-msbuild/check-bin-obj-clash/ToolLib/Tool.cs b/tests/dotnet-msbuild/check-bin-obj-clash/ToolLib/Tool.cs deleted file mode 100644 index 9726ea52f1..0000000000 --- a/tests/dotnet-msbuild/check-bin-obj-clash/ToolLib/Tool.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace ToolLib; - -public class Tool -{ - public string GetName() => "ToolLib"; -} diff --git a/tests/dotnet-msbuild/check-bin-obj-clash/ToolLib/ToolLib.csproj b/tests/dotnet-msbuild/check-bin-obj-clash/ToolLib/ToolLib.csproj deleted file mode 100644 index d7d93c0eaa..0000000000 --- a/tests/dotnet-msbuild/check-bin-obj-clash/ToolLib/ToolLib.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - net8.0 - enable - enable - - - - - diff --git a/tests/dotnet-msbuild/check-bin-obj-clash/eval.yaml b/tests/dotnet-msbuild/check-bin-obj-clash/eval.yaml deleted file mode 100644 index 604b54cb07..0000000000 --- a/tests/dotnet-msbuild/check-bin-obj-clash/eval.yaml +++ /dev/null @@ -1,37 +0,0 @@ -name: check-bin-obj-clash -description: Evaluates the dotnet-msbuild/check-bin-obj-clash skill -type: capability -config: - timeout: 160s -stimuli: - - name: Diagnose bin/obj output path clashes - prompt: Build this solution and diagnose any build failures related to output path conflicts. - environment: - files: - - src: . - dest: . - graders: - - type: output-contains - config: - substring: AppendTargetFrameworkToOutputPath - - type: output-contains - config: - substring: OutputPath - - type: output-contains - config: - substring: IntermediateOutputPath - - type: prompt - rubric: - - Identified MultiTargetLib has AppendTargetFrameworkToOutputPath=false causing net8.0 and net9.0 to write to the - same output directory - - Identified LibraryA and LibraryB share ../SharedOutput/ as OutputPath causing build artifacts to overwrite each - other - - Identified LibraryA and LibraryB share ../SharedObj/ as IntermediateOutputPath causing project.assets.json - conflicts - - Identified that ConsumerApp's ProjectReference to the single-targeting ToolLib sets SetTargetFramework to net8.0 — - the TFM ToolLib already targets — which re-injects a path-neutral TargetFramework global property, forking a - second ToolLib instance that builds to the same bin/obj as the solution-rooted build - - Recommended removing the redundant SetTargetFramework from the ToolLib reference (noting it is only appropriate - for multi-targeting references or overriding to a different TFM) - - Suggested giving each project unique output and intermediate output paths - - Referenced BaseIntermediateOutputPath vs IntermediateOutputPath concepts diff --git a/tests/dotnet-msbuild/eval-performance/EvalHeavy.csproj b/tests/dotnet-msbuild/eval-performance/EvalHeavy.csproj deleted file mode 100644 index 97805d8ccd..0000000000 --- a/tests/dotnet-msbuild/eval-performance/EvalHeavy.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - net8.0 - - - - - - - - - - $([System.IO.File]::ReadAllText('build-notes.txt')) - - diff --git a/tests/dotnet-msbuild/eval-performance/Program.cs b/tests/dotnet-msbuild/eval-performance/Program.cs deleted file mode 100644 index e41ee7edc2..0000000000 --- a/tests/dotnet-msbuild/eval-performance/Program.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace EvalHeavy; -public class App -{ - public static void Main() => System.Console.WriteLine("Hello"); -} diff --git a/tests/dotnet-msbuild/eval-performance/build-notes.txt b/tests/dotnet-msbuild/eval-performance/build-notes.txt deleted file mode 100644 index 8fc42adf8a..0000000000 --- a/tests/dotnet-msbuild/eval-performance/build-notes.txt +++ /dev/null @@ -1,2 +0,0 @@ -This file is read during evaluation by a property function. -Reading files during evaluation is expensive and should be avoided. diff --git a/tests/dotnet-msbuild/eval-performance/eval.yaml b/tests/dotnet-msbuild/eval-performance/eval.yaml deleted file mode 100644 index 372cae2aa4..0000000000 --- a/tests/dotnet-msbuild/eval-performance/eval.yaml +++ /dev/null @@ -1,29 +0,0 @@ -name: eval-performance -description: Evaluates the dotnet-msbuild/eval-performance skill -type: capability -config: - timeout: 2m -stimuli: - - name: Analyze MSBuild evaluation performance issues - prompt: Analyze this project for MSBuild evaluation performance issues. What patterns are causing slow project evaluation? - environment: - files: - - src: . - dest: . - graders: - - type: output-contains - config: - substring: import - - type: output-matches - config: - pattern: (glob|\*\*/\*) - - type: output-matches - config: - pattern: (evaluation|evaluate) - - type: prompt - rubric: - - Identified deep import chain (level1→level2→level3) and explained evaluation overhead from nested imports - - Identified overly broad glob pattern and explained it scans large directories like node_modules and .git - - Suggested restricting globs or using DefaultItemExcludes - - Identified property function performing file I/O during evaluation phase - - Explained difference between MSBuild evaluation phase and execution phase diff --git a/tests/dotnet-msbuild/eval-performance/imports/level1.props b/tests/dotnet-msbuild/eval-performance/imports/level1.props deleted file mode 100644 index 90543ac0a1..0000000000 --- a/tests/dotnet-msbuild/eval-performance/imports/level1.props +++ /dev/null @@ -1,6 +0,0 @@ - - - - true - - diff --git a/tests/dotnet-msbuild/eval-performance/imports/level2.props b/tests/dotnet-msbuild/eval-performance/imports/level2.props deleted file mode 100644 index 4bed2cb58d..0000000000 --- a/tests/dotnet-msbuild/eval-performance/imports/level2.props +++ /dev/null @@ -1,6 +0,0 @@ - - - - true - - diff --git a/tests/dotnet-msbuild/eval-performance/imports/level3.props b/tests/dotnet-msbuild/eval-performance/imports/level3.props deleted file mode 100644 index 75f1b550cd..0000000000 --- a/tests/dotnet-msbuild/eval-performance/imports/level3.props +++ /dev/null @@ -1,5 +0,0 @@ - - - true - - diff --git a/tests/dotnet-msbuild/msbuild-antipatterns/Directory.Build.props b/tests/dotnet-msbuild/msbuild-antipatterns/Directory.Build.props deleted file mode 100644 index 1ecf6a57fe..0000000000 --- a/tests/dotnet-msbuild/msbuild-antipatterns/Directory.Build.props +++ /dev/null @@ -1,19 +0,0 @@ - - - enable - enable - - - - - true - - - - - - - diff --git a/tests/dotnet-msbuild/msbuild-antipatterns/Directory.Build.targets b/tests/dotnet-msbuild/msbuild-antipatterns/Directory.Build.targets deleted file mode 100644 index 42d75b4eea..0000000000 --- a/tests/dotnet-msbuild/msbuild-antipatterns/Directory.Build.targets +++ /dev/null @@ -1,12 +0,0 @@ - - - - true - Contoso - Build Team - Copyright 2024 Contoso - - diff --git a/tests/dotnet-msbuild/msbuild-antipatterns/LibA/Class1.cs b/tests/dotnet-msbuild/msbuild-antipatterns/LibA/Class1.cs deleted file mode 100644 index 7f9be3006f..0000000000 --- a/tests/dotnet-msbuild/msbuild-antipatterns/LibA/Class1.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace LibA; -public class Class1 -{ - public string Greet(string name) => $"Hello, {name}!"; -} diff --git a/tests/dotnet-msbuild/msbuild-antipatterns/LibA/LibA.csproj b/tests/dotnet-msbuild/msbuild-antipatterns/LibA/LibA.csproj deleted file mode 100644 index b5b192f62c..0000000000 --- a/tests/dotnet-msbuild/msbuild-antipatterns/LibA/LibA.csproj +++ /dev/null @@ -1,46 +0,0 @@ - - - net8.0 - - - - C:\builds\output\LibA - - - - - ENABLE_LOGGING - - - - - - - - - - - ..\packages\Newtonsoft.Json.13.0.3\lib\net6.0\Newtonsoft.Json.dll - - - - - - - - - - - - diff --git a/tests/dotnet-msbuild/msbuild-antipatterns/LibB/Class2.cs b/tests/dotnet-msbuild/msbuild-antipatterns/LibB/Class2.cs deleted file mode 100644 index baa19a5ec7..0000000000 --- a/tests/dotnet-msbuild/msbuild-antipatterns/LibB/Class2.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace LibB; -public class Class2 -{ - public string Process() => new LibA.Class1().Greet("World"); -} diff --git a/tests/dotnet-msbuild/msbuild-antipatterns/LibB/LibB.csproj b/tests/dotnet-msbuild/msbuild-antipatterns/LibB/LibB.csproj deleted file mode 100644 index 886f5ef2f0..0000000000 --- a/tests/dotnet-msbuild/msbuild-antipatterns/LibB/LibB.csproj +++ /dev/null @@ -1,26 +0,0 @@ - - - net8.0 - - - - C:\builds\output\LibB - - - - - false - - - - - - - diff --git a/tests/dotnet-msbuild/msbuild-antipatterns/StyleIssues.sln b/tests/dotnet-msbuild/msbuild-antipatterns/StyleIssues.sln deleted file mode 100644 index 6f061a7ca3..0000000000 --- a/tests/dotnet-msbuild/msbuild-antipatterns/StyleIssues.sln +++ /dev/null @@ -1,11 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibA", "LibA\LibA.csproj", "{A1111111-1111-1111-1111-111111111111}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibB", "LibB\LibB.csproj", "{B2222222-2222-2222-2222-222222222222}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection -EndGlobal diff --git a/tests/dotnet-msbuild/msbuild-antipatterns/eval.yaml b/tests/dotnet-msbuild/msbuild-antipatterns/eval.yaml deleted file mode 100644 index e19b53ea14..0000000000 --- a/tests/dotnet-msbuild/msbuild-antipatterns/eval.yaml +++ /dev/null @@ -1,107 +0,0 @@ -name: msbuild-antipatterns -description: Evaluates the dotnet-msbuild/msbuild-antipatterns skill -type: capability -config: - timeout: 160s -stimuli: - - name: Review MSBuild files for anti-patterns and style issues - prompt: Review all MSBuild project files and build infrastructure (Directory.Build.props, Directory.Build.targets) in - this solution for correctness, best practices, and anti-patterns. Identify any issues that could cause subtle bugs - or unexpected behavior. - environment: - files: - - src: . - dest: . - graders: - - type: output-matches - config: - pattern: (Directory\.Build\.props|Directory\.Build\.targets) - - type: output-matches - config: - pattern: (anti-pattern|anti pattern|issue|problem) - - type: prompt - rubric: - - Identified hardcoded absolute paths for OutputPath - - Identified property defaults in Directory.Build.targets that should be in .props, causing LibB's - TreatWarningsAsErrors override to be silently ignored - - Identified TargetFramework condition in .props that silently fails because TFM is empty during .props evaluation - - Identified DefineConstants overwrites existing constants instead of appending - - Identified analyzer PackageReference missing PrivateAssets, unquoted MSBuild condition, mixed Include/Update in - same ItemGroup, or Exec instead of Message task - - Identified LibA's publish-on-build target that re-invokes the project via the task with a path-neutral - global property (_IsPublishing), forking a duplicate project instance that shares the output path and can race on - writes - - Identified LibB's ProjectReference to LibA sets SetTargetFramework to net8.0 — the TFM LibA already single-targets - — which forks a redundant LibA instance that shares LibA's output path, and recommended removing it - (SetTargetFramework is only for multi-targeting references or overriding to a different TFM) - - - name: Add a module to an F# project - prompt: | - Add a Validation.fs module to the F# project at fsharp/OrderService/ that - validates orders before processing. It should check that the order has at - least one item and that the customer name is not empty. Return a - Result with a descriptive error message on failure. Then - update Program.fs to validate the order before processing it, printing the - error if validation fails. - environment: - files: - - src: . - dest: . - graders: - - type: exit-success - - type: file-contains - config: - path: fsharp/OrderService/OrderService.fsproj - value: Validation.fs - - type: prompt - rubric: - - Created Validation.fs with a validation function returning Result - - Inserted Compile Include="Validation.fs" AFTER Domain.fs and BEFORE Program.fs in the .fsproj - - Did NOT place Validation.fs after Program.fs in the Compile item list - - Updated Program.fs to call the validation function before processing - - Ran dotnet build and it succeeded - - - name: Fix broken file order causing FS0039 - prompt: | - The F# project at fsharp/BrokenOrder/ fails to build. Diagnose and fix the issue. - environment: - files: - - src: . - dest: . - graders: - - type: exit-success - - type: file-contains - config: - path: fsharp/BrokenOrder/BrokenOrder.fsproj - value: Domain.fs - - type: prompt - rubric: - - Ran dotnet build and observed FS0039 or similar 'not defined' errors - - Identified that the failure is caused by wrong file order in the .fsproj — Services.fs is listed before Domain.fs - - Reordered Compile items so Domain.fs appears before Services.fs in the .fsproj - - Did NOT modify any .fs source files to work around the ordering issue - - Ran dotnet build after the fix and confirmed it succeeds - - - name: Add a signature file to define public API - prompt: | - Add a signature file (Domain.fsi) for the Domain module in the F# project at - fsharp/OrderService/ to explicitly define its public API surface. The - signature should expose all types and keep the module's public contract - clear. Make sure the project still builds after adding the signature file. - environment: - files: - - src: . - dest: . - graders: - - type: exit-success - - type: file-contains - config: - path: fsharp/OrderService/OrderService.fsproj - value: Domain.fsi - - type: prompt - rubric: - - Created Domain.fsi with type signatures matching the types in Domain.fs - - Inserted Compile Include="Domain.fsi" immediately BEFORE Domain.fs in the .fsproj - - Did NOT place Domain.fsi after Domain.fs in the Compile item list - - The .fsi file contains type declarations (not implementation code) - - The project builds successfully with the signature file present diff --git a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/BrokenOrder/BrokenOrder.fsproj b/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/BrokenOrder/BrokenOrder.fsproj deleted file mode 100644 index 78119696dc..0000000000 --- a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/BrokenOrder/BrokenOrder.fsproj +++ /dev/null @@ -1,11 +0,0 @@ - - - Exe - net8.0 - - - - - - - diff --git a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/BrokenOrder/Domain.fs b/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/BrokenOrder/Domain.fs deleted file mode 100644 index 3e75356248..0000000000 --- a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/BrokenOrder/Domain.fs +++ /dev/null @@ -1,15 +0,0 @@ -module BrokenOrder.Domain - -type OrderId = OrderId of int - -type OrderItem = { - Name: string - Quantity: int - Price: decimal -} - -type Order = { - Id: OrderId - CustomerName: string - Items: OrderItem list -} diff --git a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/BrokenOrder/Program.fs b/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/BrokenOrder/Program.fs deleted file mode 100644 index fd677e8097..0000000000 --- a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/BrokenOrder/Program.fs +++ /dev/null @@ -1,14 +0,0 @@ -open BrokenOrder.Domain -open BrokenOrder.Services - -let order = { - Id = OrderId 1 - CustomerName = "Alice" - Items = [ - { Name = "Widget"; Quantity = 2; Price = 9.99m } - { Name = "Gadget"; Quantity = 1; Price = 24.99m } - ] -} - -let total = processOrder order -printfn "Order total: $%M" total diff --git a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/BrokenOrder/Services.fs b/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/BrokenOrder/Services.fs deleted file mode 100644 index 5b4bcbaa37..0000000000 --- a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/BrokenOrder/Services.fs +++ /dev/null @@ -1,12 +0,0 @@ -module BrokenOrder.Services - -open BrokenOrder.Domain - -let calculateTotal (order: Order) = - order.Items - |> List.sumBy (fun item -> item.Price * decimal item.Quantity) - -let processOrder (order: Order) = - let total = calculateTotal order - printfn "Processing order for %s: $%M" order.CustomerName total - total diff --git a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/Directory.Build.props b/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/Directory.Build.props deleted file mode 100644 index c2880db9d1..0000000000 --- a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/Directory.Build.props +++ /dev/null @@ -1,6 +0,0 @@ - - - diff --git a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/Directory.Build.targets b/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/Directory.Build.targets deleted file mode 100644 index 8440e88187..0000000000 --- a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/Directory.Build.targets +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/OrderService/Domain.fs b/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/OrderService/Domain.fs deleted file mode 100644 index d7f3263a67..0000000000 --- a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/OrderService/Domain.fs +++ /dev/null @@ -1,15 +0,0 @@ -module OrderService.Domain - -type OrderId = OrderId of int - -type OrderItem = { - Name: string - Quantity: int - Price: decimal -} - -type Order = { - Id: OrderId - CustomerName: string - Items: OrderItem list -} diff --git a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/OrderService/OrderService.fsproj b/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/OrderService/OrderService.fsproj deleted file mode 100644 index dda1176034..0000000000 --- a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/OrderService/OrderService.fsproj +++ /dev/null @@ -1,11 +0,0 @@ - - - Exe - net8.0 - - - - - - - diff --git a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/OrderService/Program.fs b/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/OrderService/Program.fs deleted file mode 100644 index 2025e9320c..0000000000 --- a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/OrderService/Program.fs +++ /dev/null @@ -1,14 +0,0 @@ -open OrderService.Domain -open OrderService.Services - -let order = { - Id = OrderId 1 - CustomerName = "Alice" - Items = [ - { Name = "Widget"; Quantity = 2; Price = 9.99m } - { Name = "Gadget"; Quantity = 1; Price = 24.99m } - ] -} - -let total = processOrder order -printfn "Order total: $%M" total diff --git a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/OrderService/Services.fs b/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/OrderService/Services.fs deleted file mode 100644 index ed2963c36c..0000000000 --- a/tests/dotnet-msbuild/msbuild-antipatterns/fsharp/OrderService/Services.fs +++ /dev/null @@ -1,12 +0,0 @@ -module OrderService.Services - -open OrderService.Domain - -let calculateTotal (order: Order) = - order.Items - |> List.sumBy (fun item -> item.Price * decimal item.Quantity) - -let processOrder (order: Order) = - let total = calculateTotal order - printfn "Processing order for %s: $%M" order.CustomerName total - total diff --git a/tests/dotnet-test/migrate-static-to-wrapper/eval.yaml b/tests/dotnet-test/migrate-static-to-wrapper/eval.yaml deleted file mode 100644 index 4d418d93bb..0000000000 --- a/tests/dotnet-test/migrate-static-to-wrapper/eval.yaml +++ /dev/null @@ -1,183 +0,0 @@ -name: migrate-static-to-wrapper -description: Evaluates the dotnet-test/migrate-static-to-wrapper skill -type: capability -config: - timeout: 3m -stimuli: - - name: Migrate DateTime.UtcNow to TimeProvider in a service class - prompt: > - I have a CouponService that uses DateTime.UtcNow in several places. - TimeProvider is already registered in my DI container. Can you replace - all the DateTime.UtcNow calls with TimeProvider and add the constructor - parameter? - environment: - files: - - src: ./fixtures/ready-to-migrate - dest: ReadyToMigrate - graders: - - type: file-contains - config: - path: "**/CouponService.cs" - value: TimeProvider - - type: file-not-contains - config: - path: "**/CouponService.cs" - value: DateTime.UtcNow - - type: exit-success - - type: prompt - rubric: - - Replaced all DateTime.UtcNow calls in CouponService.cs with TimeProvider calls - - Added TimeProvider as a constructor parameter to CouponService - - Stored TimeProvider in a readonly field following the class's existing naming convention - - Did not change the behavior of any method — only the time source changed - - Did not modify Program.cs DI registration since TimeProvider was already registered - - - name: Migrate only in scoped files, leaving others untouched - prompt: > - I want to migrate DateTime.UtcNow to TimeProvider, but only in - CouponService.cs for now. Don't touch AuditLogger.cs yet — I'll do that - in a separate pass. TimeProvider is already in my DI container. - environment: - files: - - src: ./fixtures/ready-to-migrate - dest: ReadyToMigrate - graders: - - type: file-contains - config: - path: "**/CouponService.cs" - value: TimeProvider - - type: file-contains - config: - path: "**/AuditLogger.cs" - value: DateTime.UtcNow - - type: exit-success - - type: prompt - rubric: - - Migrated DateTime.UtcNow to TimeProvider in CouponService.cs - - Left AuditLogger.cs completely untouched with DateTime.UtcNow calls still present - - Respected the scope boundary the user specified - - Told the user which file was migrated and which was deliberately left alone, so the remaining work is not - silently dropped - - - name: Decline migration when wrapper does not exist yet - prompt: > - Replace all File.ReadAllText calls in my project with IFileSystem. Just - do the bulk replacement across all files. - environment: - files: - - src: ./fixtures/decline-no-wrapper/MyProject.csproj - dest: MyProject/MyProject.csproj - - src: ./fixtures/decline-no-wrapper/DataLoader.cs - dest: MyProject/DataLoader.cs - graders: - - type: output-matches - config: - pattern: (System\.IO\.Abstractions|package|install|not.*registered|not.*referenced|add.*package) - - type: prompt - rubric: - - Identified that System.IO.Abstractions NuGet package is not referenced in the project - - Did not blindly replace File.ReadAllText with IFileSystem calls that would not compile - - Recommended installing the package and registering IFileSystem before migrating - - - name: Preserve DateTimeKind when migrating to TimeProvider - prompt: > - Migrate the DateTime.UtcNow calls in CouponService.cs to the TimeProvider that is - already registered in DI. This is a pure refactor — the values stored on Coupon must - behave exactly as they do today. - environment: - files: - - src: ./fixtures/ready-to-migrate - dest: ReadyToMigrate - graders: - - type: file-contains - config: - path: "**/CouponService.cs" - value: UtcDateTime - - type: file-not-contains - config: - path: "**/CouponService.cs" - value: DateTime.UtcNow - - type: exit-success - - type: prompt - rubric: - - Converted the DateTimeOffset from GetUtcNow() back to DateTime in a way that leaves the stored values with - the same DateTimeKind they had before (Utc), so no consumer observes a behavior change - - Did not use the plain .DateTime property, which would silently downgrade the Kind to Unspecified - - Left CreatedAt and ExpiresAt typed as DateTime instead of widening them to DateTimeOffset - - Kept the behavior of CreateCoupon, IsValid and TimeUntilExpiry identical apart from the time source - - Restricted the change to the DateTime.UtcNow call sites the user named, leaving the intentional local-time - call untouched - - - name: Migrate a static helper class without breaking its callers - prompt: > - RetentionPolicy is a static class that calls DateTime.UtcNow in three places, which makes - it impossible to unit test. Make it testable using TimeProvider. About forty call sites - still call RetentionPolicy.IsExpired(...) and similar directly, and I cannot update them - in this change. - environment: - files: - - src: ./fixtures/static-helper - dest: StaticHelper - graders: - - type: file-contains - config: - path: "**/RetentionPolicy.cs" - value: TimeProvider - - type: file-contains - config: - path: "**/RetentionPolicy.cs" - value: static - - type: exit-success - - type: prompt - rubric: - - Kept RetentionPolicy a static class and kept every method callable as RetentionPolicy.Method(...) - - Made the time source swappable on RetentionPolicy itself, so a test can substitute a fake clock and assert - against the static API directly without routing through a new type - - Defaulted the seam to TimeProvider.System so existing callers behave exactly as before - - Replaced all three DateTime.UtcNow call sites with the seam - - Did not convert the static class into an instance class or change any public method signature — static - classes cannot take constructors, so the ambient context seam is used instead of converting the type - - - name: Add the required using directive and update tests with a test double - prompt: > - Billing/Services/SubscriptionService.cs still calls DateTime.UtcNow directly. I already - have an IClock seam under Billing/Abstractions and it is registered in my composition - root. Migrate SubscriptionService to take IClock through its constructor and fix - Billing.Tests so the project still builds and the tests still pass. Only touch - SubscriptionService and its tests — the rest of the project is a later pass. - environment: - files: - - src: ./fixtures/with-tests - dest: WithTests - graders: - - type: file-contains - config: - path: "**/SubscriptionService.cs" - value: Billing.Abstractions - - type: file-not-contains - config: - path: "**/SubscriptionService.cs" - value: DateTime.UtcNow - - type: file-contains - config: - path: "**/SubscriptionServiceTests.cs" - value: Clock - - type: file-contains - config: - path: "**/InvoiceService.cs" - value: DateTime.UtcNow - - type: exit-success - - type: prompt - rubric: - - Added the required using directive for the Billing.Abstractions namespace to SubscriptionService.cs so - the IClock type resolves without fully qualifying it - - Injected IClock through the SubscriptionService constructor and stored it in a readonly field that follows - the existing naming convention - - Replaced every DateTime.UtcNow call site in SubscriptionService with the injected clock - - Test files were updated with an appropriate test double - a hand-rolled fake IClock or a mock - rather than - the production SystemClock or the real system time - - Ran the build and the tests, and reported the result that the commands actually produced - - Kept the change to the single class the user scoped it to instead of migrating the whole project or - namespace in one run, and left InvoiceService on DateTime.UtcNow - - Reported the changes as a migration summary — which production files changed, which test files changed, and - what was deliberately left out of scope diff --git a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/decline-no-wrapper/DataLoader.cs b/tests/dotnet-test/migrate-static-to-wrapper/fixtures/decline-no-wrapper/DataLoader.cs deleted file mode 100644 index b328f6bf72..0000000000 --- a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/decline-no-wrapper/DataLoader.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace MyProject; -public class DataLoader -{ - public string Load(string path) => File.ReadAllText(path); -} diff --git a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/decline-no-wrapper/MyProject.csproj b/tests/dotnet-test/migrate-static-to-wrapper/fixtures/decline-no-wrapper/MyProject.csproj deleted file mode 100644 index 555ae434a7..0000000000 --- a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/decline-no-wrapper/MyProject.csproj +++ /dev/null @@ -1,5 +0,0 @@ - - - net10.0 - - diff --git a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/ready-to-migrate/Program.cs b/tests/dotnet-test/migrate-static-to-wrapper/fixtures/ready-to-migrate/Program.cs deleted file mode 100644 index 64135a778f..0000000000 --- a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/ready-to-migrate/Program.cs +++ /dev/null @@ -1,6 +0,0 @@ -var builder = WebApplication.CreateBuilder(args); - -builder.Services.AddSingleton(TimeProvider.System); - -var app = builder.Build(); -app.Run(); diff --git a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/ready-to-migrate/ReadyToMigrate.csproj b/tests/dotnet-test/migrate-static-to-wrapper/fixtures/ready-to-migrate/ReadyToMigrate.csproj deleted file mode 100644 index 9a04a31ebe..0000000000 --- a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/ready-to-migrate/ReadyToMigrate.csproj +++ /dev/null @@ -1,7 +0,0 @@ - - - net10.0 - enable - enable - - diff --git a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/ready-to-migrate/Services/AuditLogger.cs b/tests/dotnet-test/migrate-static-to-wrapper/fixtures/ready-to-migrate/Services/AuditLogger.cs deleted file mode 100644 index 5a8c666f3d..0000000000 --- a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/ready-to-migrate/Services/AuditLogger.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ReadyToMigrate.Services; - -public class AuditLogger -{ - public void LogAction(string userId, string action) - { - var timestamp = DateTime.UtcNow; - var entry = $"[{timestamp:O}] User={userId} Action={action}"; - Console.WriteLine(entry); - } -} diff --git a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/ready-to-migrate/Services/CouponService.cs b/tests/dotnet-test/migrate-static-to-wrapper/fixtures/ready-to-migrate/Services/CouponService.cs deleted file mode 100644 index b9b7583917..0000000000 --- a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/ready-to-migrate/Services/CouponService.cs +++ /dev/null @@ -1,51 +0,0 @@ -namespace ReadyToMigrate.Services; - -public class CouponService -{ - private readonly ILogger _logger; - - public CouponService(ILogger logger) - { - _logger = logger; - } - - public Coupon CreateCoupon(string code, int validDays) - { - return new Coupon - { - Code = code, - CreatedAt = DateTime.UtcNow, - ExpiresAt = DateTime.UtcNow.AddDays(validDays) - }; - } - - public bool IsValid(Coupon coupon) - { - if (DateTime.UtcNow > coupon.ExpiresAt) - { - _logger.LogInformation("Coupon {Code} expired at {Expiry}", coupon.Code, coupon.ExpiresAt); - return false; - } - return true; - } - - public bool IsRedeemableToday(Coupon coupon) - { - // Intentionally uses local-time semantics (DateTime.Now) — redemption is - // judged against the storefront's local calendar day, not UTC. - return coupon.ExpiresAt.Date >= DateTime.Now.Date; - } - - public TimeSpan TimeUntilExpiry(Coupon coupon) - { - var remaining = coupon.ExpiresAt - DateTime.UtcNow; - return remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero; - } -} - -public class Coupon -{ - public string Code { get; set; } = ""; - public DateTime CreatedAt { get; set; } - public DateTime ExpiresAt { get; set; } -} diff --git a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/static-helper/StaticHelper.csproj b/tests/dotnet-test/migrate-static-to-wrapper/fixtures/static-helper/StaticHelper.csproj deleted file mode 100644 index 1a57862983..0000000000 --- a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/static-helper/StaticHelper.csproj +++ /dev/null @@ -1,7 +0,0 @@ - - - net10.0 - enable - enable - - diff --git a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/static-helper/Utilities/RetentionPolicy.cs b/tests/dotnet-test/migrate-static-to-wrapper/fixtures/static-helper/Utilities/RetentionPolicy.cs deleted file mode 100644 index 0d2e486cff..0000000000 --- a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/static-helper/Utilities/RetentionPolicy.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace StaticHelper.Utilities; - -/// -/// Called from ~40 call sites across the codebase as RetentionPolicy.IsExpired(...). -/// Callers must keep working unchanged. -/// -public static class RetentionPolicy -{ - public static bool IsExpired(DateTime createdAtUtc, int retentionDays) - { - return DateTime.UtcNow > createdAtUtc.AddDays(retentionDays); - } - - public static DateTime NextPurgeWindow() - { - var now = DateTime.UtcNow; - return now.Date.AddDays(1).AddHours(2); - } - - public static string DescribeAge(DateTime createdAtUtc) - { - var age = DateTime.UtcNow - createdAtUtc; - return age.TotalDays >= 1 - ? $"{(int)age.TotalDays} day(s) old" - : $"{(int)age.TotalHours} hour(s) old"; - } -} diff --git a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing.Tests/Billing.Tests.csproj b/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing.Tests/Billing.Tests.csproj deleted file mode 100644 index 4f98e9e990..0000000000 --- a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing.Tests/Billing.Tests.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - net10.0 - enable - enable - false - - - - - - - - diff --git a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing.Tests/SubscriptionServiceTests.cs b/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing.Tests/SubscriptionServiceTests.cs deleted file mode 100644 index f4def7ca06..0000000000 --- a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing.Tests/SubscriptionServiceTests.cs +++ /dev/null @@ -1,46 +0,0 @@ -using Billing.Services; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Billing.Tests; - -[TestClass] -public sealed class SubscriptionServiceTests -{ - [TestMethod] - public void Start_RenewsAtIsStartPlusTerm() - { - var service = new SubscriptionService(); - - var subscription = service.Start("pro", 30); - - Assert.AreEqual(30d, (subscription.RenewsAt - subscription.StartedAt).TotalDays, 0.001); - } - - [TestMethod] - public void IsActive_ReturnsFalse_WhenRenewalDateHasPassed() - { - var service = new SubscriptionService(); - var subscription = new Subscription - { - PlanId = "pro", - StartedAt = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc), - RenewsAt = new DateTime(2020, 2, 1, 0, 0, 0, DateTimeKind.Utc) - }; - - Assert.IsFalse(service.IsActive(subscription)); - } - - [TestMethod] - public void DaysUntilRenewal_ReturnsZero_WhenRenewalDateHasPassed() - { - var service = new SubscriptionService(); - var subscription = new Subscription - { - PlanId = "pro", - StartedAt = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc), - RenewsAt = new DateTime(2020, 2, 1, 0, 0, 0, DateTimeKind.Utc) - }; - - Assert.AreEqual(0, service.DaysUntilRenewal(subscription)); - } -} diff --git a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Abstractions/IClock.cs b/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Abstractions/IClock.cs deleted file mode 100644 index 612fd6a39a..0000000000 --- a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Abstractions/IClock.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Billing.Abstractions; - -/// -/// Ambient clock seam. Registered as a singleton in the composition root. -/// -public interface IClock -{ - DateTime UtcNow { get; } -} diff --git a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Abstractions/SystemClock.cs b/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Abstractions/SystemClock.cs deleted file mode 100644 index 1f63e4ec0b..0000000000 --- a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Abstractions/SystemClock.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Billing.Abstractions; - -public sealed class SystemClock : IClock -{ - public DateTime UtcNow => DateTime.UtcNow; -} diff --git a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Billing.csproj b/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Billing.csproj deleted file mode 100644 index 6c3a88719f..0000000000 --- a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Billing.csproj +++ /dev/null @@ -1,7 +0,0 @@ - - - net10.0 - enable - enable - - diff --git a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Services/InvoiceService.cs b/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Services/InvoiceService.cs deleted file mode 100644 index ca4ea04193..0000000000 --- a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Services/InvoiceService.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Billing.Services; - -/// -/// Deliberately left on the static clock — this class is scheduled for a later migration pass. -/// -public sealed class InvoiceService -{ - public DateTime NextInvoiceDate(int dayOfMonth) - { - var today = DateTime.UtcNow.Date; - var candidate = new DateTime(today.Year, today.Month, dayOfMonth, 0, 0, 0, DateTimeKind.Utc); - - return candidate > today ? candidate : candidate.AddMonths(1); - } -} diff --git a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Services/SubscriptionService.cs b/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Services/SubscriptionService.cs deleted file mode 100644 index e867852e67..0000000000 --- a/tests/dotnet-test/migrate-static-to-wrapper/fixtures/with-tests/Billing/Services/SubscriptionService.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace Billing.Services; - -public sealed class SubscriptionService -{ - public Subscription Start(string planId, int termDays) - { - var now = DateTime.UtcNow; - - return new Subscription - { - PlanId = planId, - StartedAt = now, - RenewsAt = now.AddDays(termDays) - }; - } - - public bool IsActive(Subscription subscription) => DateTime.UtcNow < subscription.RenewsAt; - - public int DaysUntilRenewal(Subscription subscription) - { - var remaining = subscription.RenewsAt - DateTime.UtcNow; - return remaining > TimeSpan.Zero ? (int)Math.Ceiling(remaining.TotalDays) : 0; - } -} - -public sealed class Subscription -{ - public string PlanId { get; set; } = ""; - - public DateTime StartedAt { get; set; } - - public DateTime RenewsAt { get; set; } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/.gitignore b/tests/dotnet-upgrade/dotnet-aot-compat/after/.gitignore deleted file mode 100644 index cd42ee34e8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -bin/ -obj/ diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmClient.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmClient.cs deleted file mode 100644 index 2993823501..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmClient.cs +++ /dev/null @@ -1,315 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups; -using Azure.ResourceManager.Resources; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager -{ - /// - /// The entry point for all ARM clients. - /// - public partial class ArmClient - { - private TenantResource _tenant; - private SubscriptionResource _defaultSubscription; - private readonly ClientDiagnostics _subscriptionClientDiagnostics; - private bool? _canUseTagResource; - - internal virtual Dictionary ApiVersionOverrides { get; } = new Dictionary(); - internal ConcurrentDictionary> ResourceApiVersionCache { get; } = new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase); - internal ConcurrentDictionary NamespaceVersionCache { get; } = new ConcurrentDictionary(); - - /// - /// Initializes a new instance of the class for mocking. - /// - protected ArmClient() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// A credential used to authenticate to an Azure Service. - /// If is null. -#pragma warning disable AZC0007 // DO provide a minimal constructor that takes only the parameters required to connect to the service. - public ArmClient(TokenCredential credential) : this(credential, default, default) -#pragma warning restore AZC0007 // DO provide a minimal constructor that takes only the parameters required to connect to the service. - { - } - - /// - /// Initializes a new instance of the class. - /// - /// A credential used to authenticate to an Azure Service. - /// The id of the default Azure subscription. - /// If is null. - public ArmClient(TokenCredential credential, string defaultSubscriptionId) : this(credential, defaultSubscriptionId, default) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// A credential used to authenticate to an Azure Service. - /// The id of the default Azure subscription. - /// The client parameters to use in these operations. - /// If is null. - public ArmClient(TokenCredential credential, string defaultSubscriptionId, ArmClientOptions options) - { - Argument.AssertNotNull(credential, nameof(credential)); - - options ??= new ArmClientOptions(); - ArmEnvironment environment = options.Environment.HasValue ? options.Environment.Value : ArmEnvironment.AzurePublicCloud; - - Argument.AssertNotNull(environment.Endpoint, nameof(environment.Endpoint)); - - Endpoint = environment.Endpoint; - - Pipeline = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(credential, environment.DefaultScope)); - - Diagnostics = options.Diagnostics; - _subscriptionClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager", SubscriptionResource.ResourceType.Namespace, Diagnostics); - - CopyApiVersionOverrides(options); - - _tenant = new TenantResource(this); - _defaultSubscription = string.IsNullOrWhiteSpace(defaultSubscriptionId) ? null : - new SubscriptionResource(this, SubscriptionResource.CreateResourceIdentifier(defaultSubscriptionId)); - } - - internal virtual bool CanUseTagResource(CancellationToken cancellationToken = default) - { - if (_canUseTagResource == null) - { - var tagRp = GetDefaultSubscription(cancellationToken).GetResourceProvider(TagResource.ResourceType.Namespace, cancellationToken: cancellationToken); - _canUseTagResource = tagRp.Value.Data.ResourceTypes.Any(rp => rp.ResourceType == TagResource.ResourceType.Type); - } - return _canUseTagResource.Value; - } - - internal virtual async Task CanUseTagResourceAsync(CancellationToken cancellationToken = default) - { - if (_canUseTagResource == null) - { - var tagRp = await GetDefaultSubscription(cancellationToken).GetResourceProviderAsync(TagResource.ResourceType.Namespace, cancellationToken: cancellationToken).ConfigureAwait(false); - _canUseTagResource = tagRp.Value.Data.ResourceTypes.Any(rp => rp.ResourceType == TagResource.ResourceType.Type); - } - return _canUseTagResource.Value; - } - - private void CopyApiVersionOverrides(ArmClientOptions options) - { - foreach (var keyValuePair in options.ResourceApiVersionOverrides) - { - ApiVersionOverrides.Add(keyValuePair.Key, keyValuePair.Value); - } - } - - /// - /// Gets the api version override if it has been set for the current client options. - /// - /// The resource type to get the version for. - /// The api version to variable to set. - internal virtual bool TryGetApiVersion(ResourceType resourceType, out string apiVersion) - { - return ApiVersionOverrides.TryGetValue(resourceType, out apiVersion); - } - - /// - /// Gets the diagnostic options used for this client. - /// - internal virtual DiagnosticsOptions Diagnostics { get; } - - /// - /// Gets the base URI of the service. - /// - internal virtual Uri Endpoint { get; private set; } - - /// - /// Gets the HTTP pipeline. - /// - internal virtual HttpPipeline Pipeline { get; private set; } - - /// - /// Gets the Azure subscriptions. - /// - /// Subscription collection. - public virtual SubscriptionCollection GetSubscriptions() => _tenant.GetSubscriptions(); - - /// - /// Gets the tenants. - /// - /// Tenant collection. - public virtual TenantCollection GetTenants() - { - return new TenantCollection(this); - } - - /// - /// Gets the default subscription. - /// - /// Resource operations of the Subscription. -#pragma warning disable AZC0015 // Unexpected client method return type. - public virtual SubscriptionResource GetDefaultSubscription(CancellationToken cancellationToken = default) -#pragma warning restore AZC0015 // Unexpected client method return type. - { - using var scope = _subscriptionClientDiagnostics.CreateScope("ArmClient.GetDefaultSubscription"); - scope.Start(); - try - { - if (_defaultSubscription == null) - { - _defaultSubscription = GetSubscriptions().GetAll(cancellationToken).FirstOrDefault(); - } - else if (_defaultSubscription.HasData) - { - return _defaultSubscription; - } - else - { - _defaultSubscription = _defaultSubscription.Get(cancellationToken); - } - if (_defaultSubscription is null) - { - throw new InvalidOperationException("No subscriptions found for the given credentials"); - } - return _defaultSubscription; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets the default subscription. - /// - /// Resource operations of the Subscription. -#pragma warning disable AZC0015 // Unexpected client method return type. - public virtual async Task GetDefaultSubscriptionAsync(CancellationToken cancellationToken = default) -#pragma warning restore AZC0015 // Unexpected client method return type. - { - using var scope = _subscriptionClientDiagnostics.CreateScope("ArmClient.GetDefaultSubscription"); - scope.Start(); - try - { - if (_defaultSubscription == null) - { - _defaultSubscription = await GetSubscriptions().GetAllAsync(cancellationToken).FirstOrDefaultAsync(_ => true, cancellationToken).ConfigureAwait(false); - } - else if (_defaultSubscription.HasData) - { - return _defaultSubscription; - } - else - { - _defaultSubscription = await _defaultSubscription.GetAsync(cancellationToken).ConfigureAwait(false); - } - if (_defaultSubscription is null) - { - throw new InvalidOperationException("No subscriptions found for the given credentials"); - } - return _defaultSubscription; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Gets a collection of GenericResources. - /// An object representing collection of GenericResources and their operations. - public virtual GenericResourceCollection GetGenericResources() => _tenant.GetGenericResources(); - - /// Gets all resource providers for a subscription. - /// [This parameter is no longer supported.] The number of results to return. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - [ForwardsClientCalls] - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("This method is obsolete as the `top` parameter is not supported by service and will be removed in a future release.", false)] - public virtual Pageable GetTenantResourceProviders(int? top, string expand, CancellationToken cancellationToken = default) => _tenant.GetTenantResourceProviders(expand, cancellationToken); - - /// Gets all resource providers for a subscription. - /// [This parameter is no longer supported.] The number of results to return. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - [ForwardsClientCalls] - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("This method is obsolete as the `top` parameter is not supported by service and will be removed in a future release.", false)] - public virtual AsyncPageable GetTenantResourceProvidersAsync(int? top, string expand, CancellationToken cancellationToken = default) => _tenant.GetTenantResourceProvidersAsync(expand, cancellationToken); - - /// Gets all resource providers for a subscription. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - [ForwardsClientCalls] - public virtual Pageable GetTenantResourceProviders(string expand = null, CancellationToken cancellationToken = default) => _tenant.GetTenantResourceProviders(expand, cancellationToken); - - /// Gets all resource providers for a subscription. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - [ForwardsClientCalls] - public virtual AsyncPageable GetTenantResourceProvidersAsync(string expand = null, CancellationToken cancellationToken = default) => _tenant.GetTenantResourceProvidersAsync(expand, cancellationToken); - - /// Gets the specified resource provider at the tenant level. - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - [ForwardsClientCalls] - public virtual Response GetTenantResourceProvider(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) => _tenant.GetTenantResourceProvider(resourceProviderNamespace, expand, cancellationToken); - - /// Gets the specified resource provider at the tenant level. - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - [ForwardsClientCalls] - public virtual async Task> GetTenantResourceProviderAsync(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) => await _tenant.GetTenantResourceProviderAsync(resourceProviderNamespace, expand, cancellationToken).ConfigureAwait(false); - - /// - /// Gets the management group collection for this tenant. - /// - /// A collection of the management groups. - public virtual ManagementGroupCollection GetManagementGroups() => _tenant.GetManagementGroups(); - - /// - /// Gets a client using this instance of ArmClient to copy the client settings from. - /// - /// The type of that will be constructed. - /// Delegate method that will construct the client. - [EditorBrowsable(EditorBrowsableState.Never)] - public virtual T GetResourceClient(Func resourceFactory) - where T : ArmResource - { - return resourceFactory(); - } - - private readonly ConcurrentDictionary _clientCache = new ConcurrentDictionary(); - - /// - /// Gets a cached client to use for extension methods. - /// - /// The type of client to get. - /// The constructor factory for the client. - [EditorBrowsable(EditorBrowsableState.Never)] - public virtual T GetCachedClient(Func clientFactory) - where T : class - { - return _clientCache.GetOrAdd(typeof(T), (type) => { return clientFactory(this); }) as T; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmClientOptions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmClientOptions.cs deleted file mode 100644 index 6b60ffcab6..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmClientOptions.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Resources; -using Azure.ResourceManager; - -namespace Azure.ResourceManager -{ - /// - /// A class representing Azure resource manager client options. - /// -#pragma warning disable AZC0008 // ClientOptions should have a nested enum called ServiceVersion - public sealed class ArmClientOptions : ClientOptions -#pragma warning restore AZC0008 // ClientOptions should have a nested enum called ServiceVersion - { - internal IDictionary ResourceApiVersionOverrides { get; } = new Dictionary(); - - /// - /// Gets or sets Azure cloud environment. - /// - public ArmEnvironment? Environment { get; set; } - - /// - /// Sets the api version to use for a given resource type. - /// To find which API Versions are available in your environment you can use the method - /// for the provider namespace you are interested in. - /// - /// The resource type to set the version for. To determine the appropriate value, you can refer to the corresponding documentation or XML documentation comments of the API. Then, get its resource type from the Resource's ResourceType field. - /// The api version to use. - public void SetApiVersion(ResourceType resourceType, string apiVersion) - { - Argument.AssertNotNullOrEmpty(apiVersion, nameof(apiVersion)); - - ResourceApiVersionOverrides[resourceType] = apiVersion; - } - - /// - /// Sets the api versions from an Azure Stack profile. - /// - public void SetApiVersionsFromProfile(AzureStackProfile profile) - { - var assembly = Assembly.GetExecutingAssembly(); - using (Stream stream = assembly.GetManifestResourceStream(profile.GetManifestName())) - { - var span = BinaryData.FromStream(stream).ToMemory().Span; - var allProfile = JsonSerializer.Deserialize(span, ResourceManagerJsonContext.Default.DictionaryStringDictionaryStringJsonElement); - var armProfile = allProfile["resource-manager"]; - foreach (var keyValuePair in armProfile) - { - var namespaceName = keyValuePair.Key; - var element = keyValuePair.Value; - - foreach (var apiVersionProperty in element.EnumerateObject()) - { - var apiVersion = apiVersionProperty.Name; - foreach (var resourceTypeItem in apiVersionProperty.Value.EnumerateArray()) - { - string resourceTypeName = default; - foreach (var property in resourceTypeItem.EnumerateObject()) - { - if (property.NameEquals("resourceType")) - { - resourceTypeName = property.Value.GetString(); - break; - } - } - var resourceType = $"{namespaceName}/{resourceTypeName}"; - ResourceApiVersionOverrides[resourceType] = apiVersion; - } - } - } - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmCollection.cs deleted file mode 100644 index c3b5b1b084..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmCollection.cs +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Collections.Concurrent; -using System.ComponentModel; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager -{ - /// - /// Base class representing collection of resources. - /// - public abstract class ArmCollection - { - private readonly ConcurrentDictionary _clientCache = new ConcurrentDictionary(); - - /// - /// Initializes a new instance of the class for mocking. - /// - protected ArmCollection() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The client to copy settings from. - /// The id of the parent for the collection. - protected ArmCollection(ArmClient client, ResourceIdentifier id) - { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(client, nameof(client)); - - Client = client; - Id = id; - } - - /// - /// Gets the resource identifier. - /// - public virtual ResourceIdentifier Id { get; } - - /// - /// Gets the this resource client was created from. - /// - protected internal virtual ArmClient Client { get; } - - /// - /// Gets the diagnostic options for this resource client. - /// - protected internal DiagnosticsOptions Diagnostics => Client.Diagnostics; - - /// - /// Gets the pipeline for this resource client. - /// - protected internal HttpPipeline Pipeline => Client.Pipeline; - - /// - /// Gets the base uri for this resource client. - /// - protected internal Uri Endpoint => Client.Endpoint; - - /// - /// Gets the api version override if it has been set for the current client options. - /// - /// The resource type to get the version for. - /// The api version to variable to set. - protected bool TryGetApiVersion(ResourceType resourceType, out string apiVersion) => Client.TryGetApiVersion(resourceType, out apiVersion); - - /// - /// Gets a cached client to use for extension methods. - /// - /// The type of client to get. - /// The constructor factory for the client. - [EditorBrowsable(EditorBrowsableState.Never)] - public virtual T GetCachedClient(Func clientFactory) - where T : class - { - return _clientCache.GetOrAdd(typeof(T), (type) => { return clientFactory(Client); }) as T; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmEnvironment.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmEnvironment.cs deleted file mode 100644 index ccd1d5ede9..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmEnvironment.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Text.Json; -using System.ComponentModel; -using Azure.Core; - -namespace Azure.ResourceManager -{ - /// - /// ArmEnvrionment represents the information of an Azure Cloud environment. - /// - public readonly struct ArmEnvironment : IEquatable - { - // name after the `name` property of returned audience from https://management.azure.com/metadata/endpoints?api-version=2019-11-01 - /// Azure Public Cloud. - public static readonly ArmEnvironment AzurePublicCloud = new(new Uri("https://management.azure.com"), "https://management.azure.com/"); - - /// Azure China Cloud. - public static readonly ArmEnvironment AzureChina = new(new Uri("https://management.chinacloudapi.cn"), "https://management.chinacloudapi.cn"); - - /// Azure US Government. - public static readonly ArmEnvironment AzureGovernment = new(new Uri("https://management.usgovcloudapi.net"), "https://management.usgovcloudapi.net"); - - /// Azure German Cloud. - public static readonly ArmEnvironment AzureGermany = new(new Uri("https://management.microsoftazure.de"), "https://management.microsoftazure.de"); - - /// - /// Gets base URI of the management API endpoint. - /// - public readonly Uri Endpoint { get; } - - /// - /// Gets authentication audience. - /// - public readonly string Audience { get; } - - /// - /// Gets default authentication scope. - /// - public string DefaultScope { get; } - - /// - /// Construct an using the given value. - /// - /// Management API endpoint base URI. - /// Authentication audience. - public ArmEnvironment(Uri endpoint, string audience) - { - Argument.AssertNotNull(endpoint, nameof(endpoint)); - Argument.AssertNotNullOrWhiteSpace(audience, nameof(audience)); - - Endpoint = endpoint; - Audience = audience; - DefaultScope = $"{Audience}/.default"; - } - - /// Determines if two values are the same. - public static bool operator ==(ArmEnvironment left, ArmEnvironment right) => left.Equals(right); - - /// Determines if two values are not the same. internal - public static bool operator !=(ArmEnvironment left, ArmEnvironment right) => !left.Equals(right); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ArmEnvironment other && Equals(other); - - /// - public bool Equals(ArmEnvironment other) => string.Equals(Audience, other.Audience, StringComparison.Ordinal) && Endpoint.Equals(other.Endpoint); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() - { - return HashCodeBuilder.Combine(Endpoint, Audience); - } - - /// - public override string ToString() => JsonSerializer.Serialize(this, ResourceManagerJsonContext.Default.ArmEnvironment); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmOperation.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmOperation.cs deleted file mode 100644 index e7e016f29f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmOperation.cs +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.ClientModel.Primitives; -using System.Reflection; -using System; -using Azure.Core; -using Azure.Core.Pipeline; -using System.Threading.Tasks; -using System.Diagnostics.CodeAnalysis; - -namespace Azure.ResourceManager -{ - /// - public abstract class ArmOperation : Operation - { - /// - /// Rehydrates an operation from a . - /// - /// The Arm client. - /// The rehydration token. - /// The Arm client options. - /// The long-running operation. - public static ArmOperation Rehydrate(ArmClient client, RehydrationToken rehydrationToken, ArmClientOptions options = null) - { - Argument.AssertNotNull(client, nameof(client)); - Argument.AssertNotNull(rehydrationToken, nameof(rehydrationToken)); - - var nextLinkOperation = (NextLinkOperationImplementation)NextLinkOperationImplementation.Create(client.Pipeline, rehydrationToken); - var operationState = nextLinkOperation.UpdateStateAsync(async: false, default).EnsureCompleted(); - return new RehydrationOperation(nextLinkOperation, operationState); - } - - /// - /// Rehydrates an operation from a . - /// - /// The Arm client. - /// The rehydration token. - /// The Arm client options. - /// The long-running operation. - public static ArmOperation Rehydrate<[DynamicallyAccessedMembers(RehydrateMembers)] T>(ArmClient client, RehydrationToken rehydrationToken, ArmClientOptions options = null) where T : notnull - { - - Argument.AssertNotNull(client, nameof(client)); - Argument.AssertNotNull(rehydrationToken, nameof(rehydrationToken)); - - bool isResource = IsResource(); - IOperationSource source = new GenericOperationSource(client, isResource); - var nextLinkOperation = (NextLinkOperationImplementation)NextLinkOperationImplementation.Create(client.Pipeline, rehydrationToken); - var operation = NextLinkOperationImplementation.Create(source, nextLinkOperation); - var operationState = operation.UpdateStateAsync(async: false, default).EnsureCompleted(); - return new RehydrationOperation(nextLinkOperation, operationState, operation, options); - } - - /// - /// Rehydrates an operation from a . - /// - /// The Arm client. - /// The rehydration token. - /// The Arm client options. - /// The long-running operation. - public static async Task RehydrateAsync(ArmClient client, RehydrationToken rehydrationToken, ArmClientOptions options = null) - { - Argument.AssertNotNull(client, nameof(client)); - Argument.AssertNotNull(rehydrationToken, nameof(rehydrationToken)); - - var nextLinkOperation = (NextLinkOperationImplementation)NextLinkOperationImplementation.Create(client.Pipeline, rehydrationToken); - var operationState = await nextLinkOperation.UpdateStateAsync(async: true, default).ConfigureAwait(false); - return new RehydrationOperation(nextLinkOperation, operationState); - } - - const DynamicallyAccessedMemberTypes RehydrateMembers = DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors; - - /// - /// Rehydrates an operation from a . - /// - /// The Arm client. - /// The rehydration token. - /// The Arm client options. - /// The long-running operation. - public static async Task> RehydrateAsync<[DynamicallyAccessedMembers(RehydrateMembers)] T>(ArmClient client, RehydrationToken rehydrationToken, ArmClientOptions options = null) where T : notnull - { - - Argument.AssertNotNull(client, nameof(client)); - Argument.AssertNotNull(rehydrationToken, nameof(rehydrationToken)); - - bool isResource = IsResource(); - IOperationSource source = new GenericOperationSource(client, isResource); - var nextLinkOperation = (NextLinkOperationImplementation)NextLinkOperationImplementation.Create(client.Pipeline, rehydrationToken); - var operation = NextLinkOperationImplementation.Create(source, nextLinkOperation); - var operationState = await operation.UpdateStateAsync(async: true, default).ConfigureAwait(false); - return new RehydrationOperation(nextLinkOperation, operationState, operation, options); - } - - private static bool IsResource<[DynamicallyAccessedMembers(RehydrateMembers)] T>() where T : notnull - { - var isResource = typeof(T).GetConstructor( - BindingFlags.NonPublic | BindingFlags.Instance, - null, - CallingConventions.Any, - new Type[] { typeof(ArmClient), typeof(ResourceIdentifier) }, - null) is not null; - var obj = Activator.CreateInstance(typeof(T), BindingFlags.NonPublic | BindingFlags.Instance, null, null, null); - if (!isResource && obj is not IJsonModel) - { - throw new InvalidOperationException($"Type {typeof(T)} should be Resource or Model"); - } - - return isResource; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmOperationOfT.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmOperationOfT.cs deleted file mode 100644 index 5b23a5d6a7..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmOperationOfT.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - - -namespace Azure.ResourceManager -{ - /// - public abstract class ArmOperation : Operation - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmResource.cs deleted file mode 100644 index 3e5e82e19b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ArmResource.cs +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager -{ - /// - /// A class representing the operations that can be performed over a specific resource. - /// - public abstract partial class ArmResource - { - private readonly ConcurrentDictionary _clientCache = new ConcurrentDictionary(); - - /// - /// Initializes a new instance of the class for mocking. - /// - protected ArmResource() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The this resource client should be created from. - /// The identifier of the resource that is the target of operations. - protected internal ArmResource(ArmClient client, ResourceIdentifier id) - { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(client, nameof(client)); - - Client = client; - Id = id; - } - - /// - /// Gets the resource identifier. - /// - public virtual ResourceIdentifier Id { get; } - - /// - /// Gets the this resource client was created from. - /// - protected internal virtual ArmClient Client { get; } - - /// - /// Gets the diagnostic options for this resource client. - /// - protected internal DiagnosticsOptions Diagnostics => Client.Diagnostics; - - /// - /// Gets the pipeline for this resource client. - /// - protected internal HttpPipeline Pipeline => Client.Pipeline; - - /// - /// Gets the base uri for this resource client. - /// - protected internal Uri Endpoint => Client.Endpoint; - - /// - /// Gets the api version override if it has been set for the current client options. - /// - /// The resource type to get the version for. - /// The api version to variable to set. - protected virtual bool TryGetApiVersion(ResourceType resourceType, out string apiVersion) => Client.TryGetApiVersion(resourceType, out apiVersion); - - /// - /// Lists all available geo-locations. - /// - /// A token to allow the caller to cancel the call to the service. The default value is . - /// A collection of location that may take multiple service requests to iterate over. - [ForwardsClientCalls] - public virtual Response> GetAvailableLocations(CancellationToken cancellationToken = default) - { - string nameSpace = Id.ResourceType.Namespace; - string type = Id.ResourceType.Type; - Response resourcePageableProviderResponse = Client.GetTenantResourceProvider(nameSpace, null, cancellationToken); - TenantResourceProvider resourcePageableProvider = resourcePageableProviderResponse.Value; - if (resourcePageableProvider is null) - throw new InvalidOperationException($"{type} not found for {nameSpace}"); - var theResource = resourcePageableProvider.ResourceTypes.FirstOrDefault(r => type.Equals(r.ResourceType, StringComparison.Ordinal)); - if (theResource is null) - throw new InvalidOperationException($"{type} not found for {nameSpace}"); - return Response.FromValue(theResource.Locations.Select(l => new AzureLocation(l)), resourcePageableProviderResponse.GetRawResponse()); - } - - /// - /// Lists all available geo-locations. - /// - /// A token to allow the caller to cancel the call to the service. The default value is . - /// A collection of location that may take multiple service requests to iterate over. - [ForwardsClientCalls] - public virtual async Task>> GetAvailableLocationsAsync(CancellationToken cancellationToken = default) - { - string nameSpace = Id.ResourceType.Namespace; - string type = Id.ResourceType.Type; - Response resourcePageableProviderResponse = await Client.GetTenantResourceProviderAsync(nameSpace, null, cancellationToken).ConfigureAwait(false); - TenantResourceProvider resourcePageableProvider = resourcePageableProviderResponse.Value; - if (resourcePageableProvider is null) - throw new InvalidOperationException($"{type} not found for {nameSpace}"); - var theResource = resourcePageableProvider.ResourceTypes.FirstOrDefault(r => type.Equals(r.ResourceType, StringComparison.Ordinal)); - if (theResource is null) - throw new InvalidOperationException($"{type} not found for {nameSpace}"); - return Response.FromValue(theResource.Locations.Select(l => new AzureLocation(l)), resourcePageableProviderResponse.GetRawResponse()); - } - - /// - /// Gets a cached client to use for extension methods. - /// - /// The type of client to get. - /// The constructor factory for the client. - [EditorBrowsable(EditorBrowsableState.Never)] - public virtual T GetCachedClient(Func clientFactory) - where T : class - { - return _clientCache.GetOrAdd(typeof(T), (type) => { return clientFactory(Client); }) as T; - } - - /// - /// Checks to see if the TagResource API is deployed in the current environment. - /// - protected virtual bool CanUseTagResource(CancellationToken cancellationToken = default) => Client.CanUseTagResource(cancellationToken); - - /// - /// Checks to see if the TagResource API is deployed in the current environment. - /// - protected virtual Task CanUseTagResourceAsync(CancellationToken cancellationToken = default) => Client.CanUseTagResourceAsync(cancellationToken); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Assets/Profile/2020-09-01-hybrid.json b/tests/dotnet-upgrade/dotnet-aot-compat/after/Assets/Profile/2020-09-01-hybrid.json deleted file mode 100644 index d19b2f0667..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Assets/Profile/2020-09-01-hybrid.json +++ /dev/null @@ -1,678 +0,0 @@ -{ - "info": { - "name": "2020-09-01-hybrid", - "description": "Profile definition targeted for hybrid applications that could run on azure stack general availability version and azure cloud for 2010." - }, - "resource-manager": { - "microsoft.authorization": { - "2016-09-01": [ - { - "resourceType": "locks", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/locks.json" - } - ], - "2016-12-01": [ - { - "resourceType": "policyAssignments", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Authorization/stable/2016-12-01/policyAssignments.json" - }, - { - "resourceType": "policyDefinitions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Authorization/stable/2016-12-01/policyDefinitions.json" - } - ], - "2015-07-01": [ - { - "resourceType": "permissions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/authorization/resource-manager/Microsoft.Authorization/stable/2015-07-01/authorization-ClassicAdminCalls.json" - }, - { - "resourceType": "roleAssignments", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/authorization/resource-manager/Microsoft.Authorization/stable/2015-07-01/authorization-RoleAssignmentsCalls.json" - }, - { - "resourceType": "roleDefinitions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/authorization/resource-manager/Microsoft.Authorization/stable/2015-07-01/authorization-RoleDefinitionsCalls.json" - }, - { - "resourceType": "providerOperations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/authorization/resource-manager/Microsoft.Authorization/stable/2015-07-01/authorization-ProviderOperationsCalls.json" - } - ] - }, - "microsoft.commerce": { - "2015-06-01-preview": [ - { - "resourceType": "estimateResourceSpend", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/commerce/resource-manager/Microsoft.Commerce/preview/2015-06-01-preview/commerce.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/commerce/resource-manager/Microsoft.Commerce/preview/2015-06-01-preview/commerce.json" - }, - { - "resourceType": "subscriberUsageAggregates", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/commerce/resource-manager/Microsoft.Commerce/preview/2015-06-01-preview/commerce.json" - }, - { - "resourceType": "usageAggregates", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/commerce/resource-manager/Microsoft.Commerce/preview/2015-06-01-preview/commerce.json" - } - ] - }, - "microsoft.compute": { - "2020-06-01": [ - { - "resourceType": "availabilitySets", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "images", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "locations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "locations/publishers", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "locations/operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "locations/usages", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "locations/vmSizes", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "virtualMachines", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "virtualMachines/extensions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "virtualMachineScaleSets", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "virtualMachineScaleSets/extensions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "virtualmachineScaleSets/networkInterfaces", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "virtualMachineScaleSets/virtualMachines", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "virtualMachineScaleSets/virtualMachines/networkInterfaces", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - } - ], - "2019-07-01": [ - { - "resourceType": "disks", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2019-07-01/disk.json" - }, - { - "resourceType": "snapshots", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2019-07-01/disk.json" - } - ] - }, - "microsoft.databoxedge": { - "2019-08-01": [ - { - "resourceType": "dataBoxEdgeDevices", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/databoxedge/resource-manager/Microsoft.DataBoxEdge/stable/2019-08-01/databoxedge.json" - }, - { - "resourceType": "dataBoxEdgeDevices/checkNameAvailability", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/databoxedge/resource-manager/Microsoft.DataBoxEdge/stable/2019-08-01/databoxedge.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/databoxedge/resource-manager/Microsoft.DataBoxEdge/stable/2019-08-01/databoxedge.json" - } - ] - }, - "microsoft.devices": { - "2019-07-01-preview": [ - { - "resourceType": "usages", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - }, - { - "resourceType": "locations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - }, - { - "resourceType": "locations/quotas", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - }, - { - "resourceType": "locations/skus", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - }, - { - "resourceType": "checkNameAvailability", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - }, - { - "resourceType": "operationResults", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - }, - { - "resourceType": "IotHubs", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - }, - { - "resourceType": "backupProviders", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - }, - { - "resourceType": "backupProviders/operationResults", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - } - ] - }, - "microsoft.eventhubs": { - "2018-01-01-preview": [ - { - "resourceType": "availableClusterRegions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/preview/2018-01-01-preview/AvailableClusterRegions-preview.json" - }, - { - "resourceType": "clusters", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/preview/2018-01-01-preview/Clusters-preview.json" - }, - { - "resourceType": "namespaces", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/preview/2018-01-01-preview/namespaces-preview.json" - } - ], - "2017-04-01": [ - { - "resourceType": "checkNameAvailability", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/stable/2017-04-01/CheckNameAvailability.json" - }, - { - "resourceType": "namespaces/authorizationRules", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/stable/2017-04-01/AuthorizationRules.json" - }, - { - "resourceType": "namespaces/eventhubs", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/stable/2017-04-01/eventhubs.json" - }, - { - "resourceType": "namespaces/eventhubs/authorizationRules", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/stable/2017-04-01/AuthorizationRules.json" - }, - { - "resourceType": "namespaces/eventhubs/consumerGroups", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/stable/2017-04-01/consumergroups.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/stable/2017-04-01/operations.json" - }, - { - "resourceType": "sku", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/stable/2017-04-01/sku.json" - } - ] - }, - "microsoft.insights": { - "2018-01-01": [ - { - "resourceType": "metricDefinitions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/monitor/resource-manager/Microsoft.Insights/stable/2018-01-01/metricDefinitions_API.json" - }, - { - "resourceType": "metrics", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/monitor/resource-manager/Microsoft.Insights/stable/2018-01-01/metrics_API.json" - } - ], - "2017-05-01-preview": [ - { - "resourceType": "diagnosticSettings", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/monitor/resource-manager/Microsoft.Insights/preview/2017-05-01-preview/diagnosticsSettings_API.json" - }, - { - "resourceType": "diagnosticSettingCategories", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/monitor/resource-manager/Microsoft.Insights/preview/2017-05-01-preview/diagnosticsSettingsCategories_API.json" - } - ], - "2015-04-01": [ - { - "resourceType": "eventCategories", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/monitor/resource-manager/Microsoft.Insights/stable/2015-04-01/eventCategories_API.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/monitor/resource-manager/Microsoft.Insights/stable/2015-04-01/operations_API.json" - } - ] - }, - "microsoft.keyvault": { - "2019-09-01": [ - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/keyvault/resource-manager/Microsoft.KeyVault/stable/2019-09-01/providers.json" - }, - { - "resourceType": "vaults", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/keyvault/resource-manager/Microsoft.KeyVault/stable/2019-09-01/keyvault.json" - }, - { - "resourceType": "vaults/accessPolicies", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/keyvault/resource-manager/Microsoft.KeyVault/stable/2019-09-01/keyvault.json" - }, - { - "resourceType": "vaults/secrets", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/keyvault/resource-manager/Microsoft.KeyVault/stable/2019-09-01/secrets.json" - } - ] - }, - "microsoft.network": { - "2018-11-01": [ - { - "resourceType": "connections", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/virtualNetworkGateway.json" - }, - { - "resourceType": "loadBalancers", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/loadBalancer.json" - }, - { - "resourceType": "localNetworkGateways", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/virtualNetworkGateway.json" - }, - { - "resourceType": "locations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/network.json" - }, - { - "resourceType": "locations/operationResults", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/network.json" - }, - { - "resourceType": "locations/operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/network.json" - }, - { - "resourceType": "locations/usages", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/network.json" - }, - { - "resourceType": "networkInterfaces", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/networkInterface.json" - }, - { - "resourceType": "networkSecurityGroups", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/networkSecurityGroup.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/operation.json" - }, - { - "resourceType": "publicIpAddresses", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/publicIpAddress.json" - }, - { - "resourceType": "routeTables", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/routeTable.json" - }, - { - "resourceType": "virtualNetworkGateways", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/virtualNetworkGateway.json" - }, - { - "resourceType": "virtualNetworks", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/virtualNetwork.json" - } - ], - "2016-04-01": [ - { - "resourceType": "dnsZones", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/dns/resource-manager/Microsoft.Network/stable/2016-04-01/dns.json" - } - ] - }, - "microsoft.resources": { - "2016-06-01": [ - { - "resourceType": "subscriptions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2016-06-01/subscriptions.json" - }, - { - "resourceType": "subscriptions/locations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2016-06-01/subscriptions.json" - }, - { - "resourceType": "tenants", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2016-06-01/subscriptions.json" - } - ], - "2019-10-01": [ - { - "resourceType": "deployments", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "deployments/operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "links", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "locations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "providers", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "resourceGroups", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "resources", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "subscriptions/operationresults", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "subscriptions/providers", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "subscriptions/resourceGroups", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "subscriptions/resourceGroups/resources", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "subscriptions/resources", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "subscriptions/tagNames", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "subscriptions/tagNames/tagValues", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - } - ] - }, - "microsoft.storage": { - "2019-06-01": [ - { - "resourceType": "checkNameAvailability", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/storage.json" - }, - { - "resourceType": "locations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/storage.json" - }, - { - "resourceType": "locations/quotas", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/storage.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/storage.json" - }, - { - "resourceType": "storageAccounts", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/storage.json" - }, - { - "resourceType": "storageAccounts/blobServices", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/storage.json" - }, - { - "resourceType": "storageAccounts/queueServices", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/storage.json" - }, - { - "resourceType": "storageAccounts/tableServices", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/storage.json" - }, - { - "resourceType": "usages", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/storage.json" - } - ] - }, - "microsoft.web": { - "2018-02-01": [ - { - "resourceType": "certificates", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/Certificates.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "checknameavailability", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/ResourceProvider.json" - }, - { - "resourceType": "metadata", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites/domainOwnershipIdentifiers", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites/extensions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites/hostNameBindings", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites/instances", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites/instances/extensions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites/slots", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites/slots/hostNameBindings", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites/slots/instances", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites/slots/instances/extensions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "serverFarms", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "serverFarms/metricDefinitions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/AppServicePlans.json" - }, - { - "resourceType": "serverFarms/metrics", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/AppServicePlans.json" - }, - { - "resourceType": "serverFarms/usages", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/AppServicePlans.json" - }, - { - "resourceType": "availableStacks", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/Provider.json" - }, - { - "resourceType": "deploymentLocations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/ResourceProvider.json" - }, - { - "resourceType": "georegions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/ResourceProvider.json" - }, - { - "resourceType": "listSitesAssignedToHostName", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/ResourceProvider.json" - }, - { - "resourceType": "publishingUsers", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/ResourceProvider.json" - }, - { - "resourceType": "recommendations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/Recommendations.json" - }, - { - "resourceType": "sourceControls", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/ResourceProvider.json" - }, - { - "resourceType": "validate", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/ResourceProvider.json" - } - ] - }, - "microsoft.containerregistry" : { - "2019-05-01": [ - { - "resourceType": "registries", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - }, - { - "resourceType": "registries/importImage", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - }, - { - "resourceType": "registries/webhooks", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - }, - { - "resourceType": "registries/webhooks/ping", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - }, - { - "resourceType": "registries/webhooks/getCallbackConfig", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - }, - { - "resourceType": "registries/webhooks/listEvents", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - }, - { - "resourceType": "registries/listCredentials", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - }, - { - "resourceType": "registries/regenerateCredential", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - }, - { - "resourceType": "checkNameAvailability", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - }, - { - "resourceType": "operations", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - } - ] - }, - "microsoft.containerservice" : { - "2020-11-01": [ - { - "resourceType": "managedclusters", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerservice/resource-manager/Microsoft.ContainerService/stable/2020-11-01/managedClusters.json" - } - ], - "2019-04-01": [ - { - "resourceType": "locations/orchestrators", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerservice/resource-manager/Microsoft.ContainerService/stable/2019-04-01/location.json" - } - ], - "2017-07-01": [ - { - "resourceType": "containerServices", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerservice/resource-manager/Microsoft.ContainerService/stable/2017-07-01/containerService.json" - } - ] - } - }, - "data-plane": { - "microsoft.keyvault": { - "7.1": [ - { - "resourceType": "secrets", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/keyvault/data-plane/Microsoft.KeyVault/stable/7.1/secrets.json" - }, - { - "resourceType": "keys", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/keyvault/data-plane/Microsoft.KeyVault/stable/7.1/keys.json" - } - ] - }, - "microsoft.containerregistry": { - "2019-08-15-preview": [ - { - "resourceType": "*", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/data-plane/Microsoft.ContainerRegistry/preview/2019-08-15/containerregistry.json" - } - ] - }, - "microsoft.storage": { - "resourceType": "*", - "2019-07-07": [] - } - } - } diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Azure.ResourceManager.csproj b/tests/dotnet-upgrade/dotnet-aot-compat/after/Azure.ResourceManager.csproj deleted file mode 100644 index a8b3ec55de..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Azure.ResourceManager.csproj +++ /dev/null @@ -1,31 +0,0 @@ - - - - net9.0 - 1.14.0-beta.1 - - 1.13.1 - Azure.ResourceManager - Microsoft Azure Resource Manager client SDK for Azure resources. - azure;management;resource - true - false - false - $(NoWarn);AZPROVISION001;SCM0005 - true - - - - - - - - - - - - - - - - diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/AzureStackProfile.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/AzureStackProfile.cs deleted file mode 100644 index 09f285c061..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/AzureStackProfile.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -namespace Azure.ResourceManager -{ - /// - /// AzureStackProfile represents the information of an Azure Stack profile. - /// - public enum AzureStackProfile - { - /// The 2020-09-01-hybrid profile. - Profile20200901Hybrid - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/BicepModelReaderWriterOptions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/BicepModelReaderWriterOptions.cs deleted file mode 100644 index eaa886e500..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/BicepModelReaderWriterOptions.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; - -namespace Azure.ResourceManager -{ - /// - /// Provides the options for reading and writing Bicep. - /// - [Experimental("AZPROVISION001")] - public class BicepModelReaderWriterOptions : ModelReaderWriterOptions - { - /// - /// Initializes a new instance of . - /// - public BicepModelReaderWriterOptions() : base("bicep") - { - } - - /// - /// The set of property overrides to apply when writing the bicep. The key of the dictionary corresponds to the - /// instance being written, and the value is a dictionary of property names to property values. - /// - public IDictionary> PropertyOverrides { get; } = new Dictionary>(); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/CodeGenAttributes.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/CodeGenAttributes.cs deleted file mode 100644 index efc951c129..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/CodeGenAttributes.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Stubs for Azure AutoRest codegen types (not available as a public NuGet package) -#nullable enable - -// GeneratorPageableHelpers is a codegen-emitted copy of PageableHelpers -namespace Azure.Core -{ - internal static class GeneratorPageableHelpers - { - public static AsyncPageable CreateAsyncPageable( - System.Func? createFirstPageRequest, - System.Func? createNextPageRequest, - System.Func valueFactory, - Pipeline.ClientDiagnostics clientDiagnostics, - Pipeline.HttpPipeline pipeline, - string scopeName, - string? itemPropertyName, - string? nextLinkPropertyName, - System.Threading.CancellationToken cancellationToken) where T : notnull - => PageableHelpers.CreateAsyncPageable(createFirstPageRequest, createNextPageRequest, valueFactory, clientDiagnostics, pipeline, scopeName, itemPropertyName, nextLinkPropertyName, cancellationToken); - - public static Pageable CreatePageable( - System.Func? createFirstPageRequest, - System.Func? createNextPageRequest, - System.Func valueFactory, - Pipeline.ClientDiagnostics clientDiagnostics, - Pipeline.HttpPipeline pipeline, - string scopeName, - string? itemPropertyName, - string? nextLinkPropertyName, - System.Threading.CancellationToken cancellationToken) where T : notnull - => PageableHelpers.CreatePageable(createFirstPageRequest, createNextPageRequest, valueFactory, clientDiagnostics, pipeline, scopeName, itemPropertyName, nextLinkPropertyName, cancellationToken); - } - - [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct)] - internal class CodeGenTypeAttribute : System.Attribute - { - public CodeGenTypeAttribute(string originalName) { } - } - - [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct, AllowMultiple = true)] - internal class CodeGenSuppressAttribute : System.Attribute - { - public CodeGenSuppressAttribute(string member, params System.Type[] parameters) { } - } - - [System.AttributeUsage(System.AttributeTargets.Assembly, AllowMultiple = true)] - internal class CodeGenSuppressTypeAttribute : System.Attribute - { - public CodeGenSuppressTypeAttribute(string typeName) { } - } - - [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Field, AllowMultiple = true)] - internal class CodeGenMemberAttribute : System.Attribute - { - public CodeGenMemberAttribute(string originalName) { } - } - - [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct, AllowMultiple = true)] - internal class CodeGenSerializationAttribute : System.Attribute - { - public CodeGenSerializationAttribute(string propertyName) { } - public string? SerializationValueHook { get; set; } - public string? DeserializationValueHook { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ArmPlan.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ArmPlan.cs deleted file mode 100644 index 35564305f8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ArmPlan.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.ComponentModel; -using System.Globalization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// - /// Representation of a publisher plan for marketplace RPs. - /// - public sealed partial class ArmPlan : IEquatable - { - /// - /// Compares this instance with another object and determines if they are equals. - /// - /// object to compare. - /// True if they are equals, otherwise false. - public bool Equals(ArmPlan other) - { - if (ReferenceEquals(other, null)) - return false; - - if (ReferenceEquals(this, other)) - return true; - - return string.Equals(Name, other.Name, StringComparison.InvariantCultureIgnoreCase) && - string.Equals(Product, other.Product, StringComparison.InvariantCultureIgnoreCase) && - string.Equals(PromotionCode, other.PromotionCode, StringComparison.InvariantCultureIgnoreCase) && - string.Equals(Publisher, other.Publisher, StringComparison.InvariantCultureIgnoreCase) && - string.Equals(Version, other.Version, StringComparison.InvariantCultureIgnoreCase); - } - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) - { - if (ReferenceEquals(this, obj)) - { - return true; - } - - if (ReferenceEquals(obj, null)) - { - return false; - } - - if (obj is not ArmPlan other) - return false; - - return Equals(other); - } - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() - { - return HashCodeBuilder.Combine( - Name?.ToLower(CultureInfo.InvariantCulture), - Publisher?.ToLower(CultureInfo.InvariantCulture), - Product?.ToLower(CultureInfo.InvariantCulture), - PromotionCode?.ToLower(CultureInfo.InvariantCulture), - Version?.ToLower(CultureInfo.InvariantCulture)); - } - - /// - /// Compares this instance with another object and determines if they are equals. - /// - /// The object on the left side of the operator. - /// The object on the right side of the operator. - /// True if they are equal, otherwise false. - public static bool operator ==(ArmPlan left, ArmPlan right) - { - if (ReferenceEquals(left, null)) - { - return ReferenceEquals(right, null); - } - - return left.Equals(right); - } - - /// - /// Compares this instance with another object and determines if they are equals. - /// - /// The object on the left side of the operator. - /// The object on the right side of the operator. - /// True if they are not equal, otherwise false. - public static bool operator !=(ArmPlan left, ArmPlan right) - { - return !(left == right); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ArmSku.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ArmSku.cs deleted file mode 100644 index ce20416eb1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ArmSku.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.ComponentModel; -using System.Globalization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// - /// A class representing SKU for resource. - /// - public sealed partial class ArmSku : IEquatable - { - /// - /// Compares this instance with another object and determines if they are equals. - /// - /// object to compare. - /// True if they are equals, otherwise false. - public bool Equals(ArmSku other) - { - if (other == null) - return false; - - if (object.ReferenceEquals(this, other)) - return true; - - return string.Equals(Name, other.Name, StringComparison.InvariantCultureIgnoreCase) && - string.Equals(Family, other.Family, StringComparison.InvariantCultureIgnoreCase) && - string.Equals(Size, other.Size, StringComparison.InvariantCultureIgnoreCase) && - (Tier.HasValue ? Tier.Value.Equals(other.Tier) : !other.Tier.HasValue) && - long.Equals(Capacity, other.Capacity); - } - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) - { - if (ReferenceEquals(this, obj)) - { - return true; - } - - if (ReferenceEquals(obj, null)) - { - return false; - } - - if (obj is not ArmSku other) - return false; - - return Equals(other); - } - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() - { - return HashCodeBuilder.Combine( - Name?.ToLower(CultureInfo.InvariantCulture), - Family?.ToLower(CultureInfo.InvariantCulture), - Size?.ToLower(CultureInfo.InvariantCulture), - Tier?.ToString().ToLower(CultureInfo.InvariantCulture), - Capacity); - } - - /// - /// Compares this instance with another object and determines if they are equals. - /// - /// The sku on the left side of the operator. - /// The sku on the right side of the operator. - /// True if they are equal, otherwise false. - public static bool operator ==(ArmSku left, ArmSku right) - { - if (ReferenceEquals(left, null)) - { - return ReferenceEquals(right, null); - } - - return left.Equals(right); - } - - /// - /// Compares this instance with another object and determines if they are not equal. - /// - /// The sku on the left side of the operator. - /// The sku on the right side of the operator. - /// True if they are not equal, otherwise false. - public static bool operator !=(ArmSku left, ArmSku right) - { - return !(left == right); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/EncryptionProperties.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/EncryptionProperties.cs deleted file mode 100644 index a5a35be565..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/EncryptionProperties.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Models -{ - // this class here is to keep the class public and add the EditorBrowsableNever attribute - // this class is exposed in resourcemanager by accident, now we hide it in resourcemanager - [Obsolete("This type is obsolete and will be removed in a future release.", false)] - [EditorBrowsable(EditorBrowsableState.Never)] - public partial class EncryptionProperties - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/EncryptionStatus.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/EncryptionStatus.cs deleted file mode 100644 index c1fc8e2bbc..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/EncryptionStatus.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Models -{ - // this class here is to keep the class public and add the EditorBrowsableNever attribute - // this class is exposed in resourcemanager by accident, now we hide it in resourcemanager - [Obsolete("This type is obsolete and will be removed in a future release.", false)] - [EditorBrowsable(EditorBrowsableState.Never)] - public readonly partial struct EncryptionStatus - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/KeyVaultProperties.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/KeyVaultProperties.cs deleted file mode 100644 index 5b49b0341a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/KeyVaultProperties.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Models -{ - // this class here is to keep the class public and add the EditorBrowsableNever attribute - // this class is exposed in resourcemanager by accident, now we hide it in resourcemanager - [Obsolete("This type is obsolete and will be removed in a future release.", false)] - [EditorBrowsable(EditorBrowsableState.Never)] - public partial class KeyVaultProperties - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentity.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentity.Serialization.cs deleted file mode 100644 index cbc31f23a0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentity.Serialization.cs +++ /dev/null @@ -1,263 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; -using Azure.ResourceManager.Models; - -[assembly: CodeGenSuppressType("ManagedServiceIdentity")] -namespace Azure.ResourceManager.Models -{ - [JsonConverter(typeof(ManagedServiceIdentityConverter))] - public partial class ManagedServiceIdentity : IJsonModel - { - internal void Write(Utf8JsonWriter writer, ModelReaderWriterOptions options, JsonSerializerOptions jOptions = null) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagedServiceIdentity)} does not support '{format}' format."); - } - - writer.WriteStartObject(); - JsonSerializer.Serialize(writer, ManagedServiceIdentityType, ResourceManagerJsonContext.Default.ManagedServiceIdentityType); - if (options.Format != "W" && Optional.IsDefined(PrincipalId)) - { - writer.WritePropertyName("principalId"u8); - writer.WriteStringValue(PrincipalId.Value); - } - if (options.Format != "W" && Optional.IsDefined(TenantId)) - { - writer.WritePropertyName("tenantId"u8); - writer.WriteStringValue(TenantId.Value); - } - if (Optional.IsCollectionDefined(UserAssignedIdentities)) - { - writer.WritePropertyName("userAssignedIdentities"u8); - writer.WriteStartObject(); - foreach (var item in UserAssignedIdentities) - { - writer.WritePropertyName(item.Key); - JsonSerializer.Serialize(writer, item.Value, ResourceManagerJsonContext.Default.UserAssignedIdentity); - } - writer.WriteEndObject(); - } - writer.WriteEndObject(); - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - Write(writer, options, null); - } - - ManagedServiceIdentity IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagedServiceIdentity)} does not support '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagedServiceIdentity(document.RootElement, options); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagedServiceIdentity)} does not support '{options.Format}' format."); - } - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ManagedServiceIdentityType), out propertyOverride); - if (Optional.IsDefined(ManagedServiceIdentityType) || hasPropertyOverride) - { - builder.Append(" type:"); - if (hasPropertyOverride) - { - builder.AppendLine($" {propertyOverride}"); - } - else - { - builder.AppendLine($" '{ManagedServiceIdentityType}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(UserAssignedIdentities), out propertyOverride); - if (UserAssignedIdentities.Any() || hasPropertyOverride) - { - builder.Append(" userAssignedIdentities:"); - builder.AppendLine(" {"); - if (hasPropertyOverride) - { - builder.AppendLine($" {propertyOverride}"); - } - else - { - foreach (var item in UserAssignedIdentities) - { - builder.Append($" {item.Key}:"); - AppendChildObject(builder, item.Value, options, 4, false); - } - } - - builder.AppendLine(" }"); - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - private void AppendChildObject(StringBuilder stringBuilder, object childObject, ModelReaderWriterOptions options, int spaces, bool indentFirstLine) - { - string indent = new string(' ', spaces); - BinaryData data = ModelReaderWriter.Write(childObject, options, AzureResourceManagerContext.Default); - string[] lines = data.ToString().Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); - bool inMultilineString = false; - for (int i = 0; i < lines.Length; i++) - { - string line = lines[i]; - if (inMultilineString) - { - if (line.Contains("'''")) - { - inMultilineString = false; - } - stringBuilder.AppendLine(line); - continue; - } - if (line.Contains("'''")) - { - inMultilineString = true; - stringBuilder.AppendLine($"{indent}{line}"); - continue; - } - if (i == 0 && !indentFirstLine) - { - stringBuilder.AppendLine($" {line}"); - } - else - { - stringBuilder.AppendLine($"{indent}{line}"); - } - } - } - - internal static ManagedServiceIdentity DeserializeManagedServiceIdentity(JsonElement element, ModelReaderWriterOptions options, JsonSerializerOptions jOptions) - { - options ??= new ModelReaderWriterOptions("W"); - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - Guid? principalId = default; - Guid? tenantId = default; - ManagedServiceIdentityType type = default; - IDictionary userAssignedIdentities = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("principalId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null || property.Value.GetString().Length == 0) - { - continue; - } - principalId = property.Value.GetGuid(); - continue; - } - if (property.NameEquals("tenantId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null || property.Value.GetString().Length == 0) - { - continue; - } - tenantId = property.Value.GetGuid(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = JsonSerializer.Deserialize($"{{{property}}}", ResourceManagerJsonContext.Default.ManagedServiceIdentityType); - continue; - } - if (property.NameEquals("userAssignedIdentities"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(new ResourceIdentifier(property0.Name), JsonSerializer.Deserialize(property0.Value.GetRawText(), ResourceManagerJsonContext.Default.UserAssignedIdentity)); - } - userAssignedIdentities = dictionary; - continue; - } - } - return new ManagedServiceIdentity(principalId, tenantId, type, userAssignedIdentities ?? new ChangeTrackingDictionary()); - } - - internal static ManagedServiceIdentity DeserializeManagedServiceIdentity(JsonElement element, ModelReaderWriterOptions options = null) - { - return DeserializeManagedServiceIdentity(element, options, null); - } - - ManagedServiceIdentity IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeManagedServiceIdentity(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagedServiceIdentity)} does not support '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class ManagedServiceIdentityConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, ManagedServiceIdentity model, JsonSerializerOptions options) - { - model.Write(writer, new ModelReaderWriterOptions("W"), options); - } - public override ManagedServiceIdentity Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeManagedServiceIdentity(document.RootElement, null, options); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentity.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentity.cs deleted file mode 100644 index 96313186cf..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentity.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// Managed service identity (system assigned and/or user assigned identities). - [PropertyReferenceType(new string[] { "UserAssignedIdentities" })] - public partial class ManagedServiceIdentity - { - /// Initializes a new instance of ManagedServiceIdentity. - /// Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). - [InitializationConstructor] - public ManagedServiceIdentity(ManagedServiceIdentityType managedServiceIdentityType) - { - ManagedServiceIdentityType = managedServiceIdentityType; - UserAssignedIdentities = new ChangeTrackingDictionary(); - } - - /// Initializes a new instance of ManagedServiceIdentity. - /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. - /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. - /// Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). - /// 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. - [SerializationConstructor] - internal ManagedServiceIdentity(Guid? principalId, Guid? tenantId, ManagedServiceIdentityType managedServiceIdentityType, IDictionary userAssignedIdentities) - { - PrincipalId = principalId; - TenantId = tenantId; - ManagedServiceIdentityType = managedServiceIdentityType; - UserAssignedIdentities = userAssignedIdentities; - } - - /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. - public Guid? PrincipalId { get; } - /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. - public Guid? TenantId { get; } - /// Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). - public ManagedServiceIdentityType ManagedServiceIdentityType { get; set; } - /// 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. - public IDictionary UserAssignedIdentities { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentityType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentityType.cs deleted file mode 100644 index 7954ef73df..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentityType.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace Azure.ResourceManager.Models -{ - /// Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). - [JsonConverter(typeof(ManagedServiceIdentityTypeConverter))] - public readonly partial struct ManagedServiceIdentityType : IEquatable - { - internal partial class ManagedServiceIdentityTypeConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, ManagedServiceIdentityType model, JsonSerializerOptions options) - { - writer.WritePropertyName("type"); - writer.WriteStringValue(model.ToString()); - } - public override ManagedServiceIdentityType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - foreach (var property in document.RootElement.EnumerateObject()) - { - if (property.Value.ValueKind == JsonValueKind.Null) - return default; - else - return new ManagedServiceIdentityType(property.Value.GetString()); - } - return null; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/SystemAssignedServiceIdentity.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/SystemAssignedServiceIdentity.cs deleted file mode 100644 index e887668292..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/SystemAssignedServiceIdentity.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ComponentModel; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// Managed service identity (either system assigned, or none). - // this class is consolidated into the ManagedServiceIdentity class. - [Obsolete("This type is obsolete and will be removed in a future release.", false)] - [EditorBrowsable(EditorBrowsableState.Never)] - public partial class SystemAssignedServiceIdentity - { - /// Initializes a new instance of SystemAssignedServiceIdentity. - /// Type of managed service identity (either system assigned, or none). - [InitializationConstructor] - public SystemAssignedServiceIdentity(SystemAssignedServiceIdentityType systemAssignedServiceIdentityType) - { - Identity = new ManagedServiceIdentity(systemAssignedServiceIdentityType.ToString()); - } - - /// Initializes a new instance of SystemAssignedServiceIdentity. - /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. - /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. - /// Type of managed service identity (either system assigned, or none). - [SerializationConstructor] - internal SystemAssignedServiceIdentity(Guid? principalId, Guid? tenantId, SystemAssignedServiceIdentityType systemAssignedServiceIdentityType) - { - Identity = new ManagedServiceIdentity(principalId, tenantId, systemAssignedServiceIdentityType.ToString(), null); - } - - /// Initializes a new instance of SystemAssignedServiceIdentity by given ManagedServiceIdentity. - internal SystemAssignedServiceIdentity(ManagedServiceIdentity managedServiceIdentity) - { - if (managedServiceIdentity == null) - { - throw new ArgumentNullException(); - } - Identity = managedServiceIdentity; - } - - internal ManagedServiceIdentity Identity { get; set; } - - /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. - public Guid? PrincipalId - { - get => Identity.PrincipalId; - } - /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. - public Guid? TenantId - { - get => Identity.TenantId; - } - /// Type of managed service identity (either system assigned, or none). - public SystemAssignedServiceIdentityType SystemAssignedServiceIdentityType - { - get => Identity.ManagedServiceIdentityType.ToString(); - set => Identity.ManagedServiceIdentityType = value.ToString(); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/SystemAssignedServiceIdentityType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/SystemAssignedServiceIdentityType.cs deleted file mode 100644 index 15fb71110a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/Models/SystemAssignedServiceIdentityType.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Models -{ - // this struct is consolidated into ManagedServiceIdentityType. - [Obsolete("This type is obsolete and will be removed in a future release.", false)] - [EditorBrowsable(EditorBrowsableState.Never)] - public readonly partial struct SystemAssignedServiceIdentityType - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/ResourceManagerModelFactory.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/ResourceManagerModelFactory.cs deleted file mode 100644 index c5d2b26469..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Custom/ResourceManagerModelFactory.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Models -{ - /// Model factory for read-only models. - public static partial class ResourceManagerModelFactory - { - /// Initializes a new instance of LocationExpanded. - /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. - /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. - /// Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). - /// 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. - /// A new instance for mocking. - public static ManagedServiceIdentity ManagedServiceIdentity(Guid? principalId = null, Guid? tenantId = null, ManagedServiceIdentityType managedServiceIdentityType = default, IDictionary userAssignedIdentities = null) - { - return new ManagedServiceIdentity(principalId, tenantId, managedServiceIdentityType, userAssignedIdentities); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/Argument.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/Argument.cs deleted file mode 100644 index 0e6dfdb59a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/Argument.cs +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; - -namespace Azure.ResourceManager -{ - internal static class Argument - { - public static void AssertNotNull(T value, string name) - { - if (value is null) - { - throw new ArgumentNullException(name); - } - } - - public static void AssertNotNull(T? value, string name) - where T : struct - { - if (!value.HasValue) - { - throw new ArgumentNullException(name); - } - } - - public static void AssertNotNullOrEmpty(IEnumerable value, string name) - { - if (value is null) - { - throw new ArgumentNullException(name); - } - if (value is ICollection collectionOfT && collectionOfT.Count == 0) - { - throw new ArgumentException("Value cannot be an empty collection.", name); - } - if (value is ICollection collection && collection.Count == 0) - { - throw new ArgumentException("Value cannot be an empty collection.", name); - } - using IEnumerator e = value.GetEnumerator(); - if (!e.MoveNext()) - { - throw new ArgumentException("Value cannot be an empty collection.", name); - } - } - - public static void AssertNotNullOrEmpty(string value, string name) - { - if (value is null) - { - throw new ArgumentNullException(name); - } - if (value.Length == 0) - { - throw new ArgumentException("Value cannot be an empty string.", name); - } - } - - public static void AssertNotNullOrWhiteSpace(string value, string name) - { - if (value is null) - { - throw new ArgumentNullException(name); - } - if (string.IsNullOrWhiteSpace(value)) - { - throw new ArgumentException("Value cannot be empty or contain only white-space characters.", name); - } - } - - public static void AssertNotDefault(ref T value, string name) - where T : struct, IEquatable - { - if (value.Equals(default)) - { - throw new ArgumentException("Value cannot be empty.", name); - } - } - - public static void AssertInRange(T value, T minimum, T maximum, string name) - where T : notnull, IComparable - { - if (minimum.CompareTo(value) > 0) - { - throw new ArgumentOutOfRangeException(name, "Value is less than the minimum allowed."); - } - if (maximum.CompareTo(value) < 0) - { - throw new ArgumentOutOfRangeException(name, "Value is greater than the maximum allowed."); - } - } - - public static void AssertEnumDefined(Type enumType, object value, string name) - { - if (!Enum.IsDefined(enumType, value)) - { - throw new ArgumentException($"Value not defined for {enumType.FullName}.", name); - } - } - - public static T CheckNotNull(T value, string name) - where T : class - { - AssertNotNull(value, name); - return value; - } - - public static string CheckNotNullOrEmpty(string value, string name) - { - AssertNotNullOrEmpty(value, name); - return value; - } - - public static void AssertNull(T value, string name, string message = null) - { - if (value != null) - { - throw new ArgumentException(message ?? "Value must be null.", name); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/BicepSerializationHelpers.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/BicepSerializationHelpers.cs deleted file mode 100644 index 633bf5b166..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/BicepSerializationHelpers.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text; - -namespace Azure.ResourceManager -{ - internal static class BicepSerializationHelpers - { - public static void AppendChildObject(StringBuilder stringBuilder, object childObject, ModelReaderWriterOptions options, int spaces, bool indentFirstLine, string formattedPropertyName) - { - string indent = new string(' ', spaces); - int emptyObjectLength = 2 + spaces + Environment.NewLine.Length + Environment.NewLine.Length; - int length = stringBuilder.Length; - bool inMultilineString = false; - - BinaryData data = ModelReaderWriter.Write(childObject, options, AzureResourceManagerContext.Default); - string[] lines = data.ToString().Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); - for (int i = 0; i < lines.Length; i++) - { - string line = lines[i]; - if (inMultilineString) - { - if (line.Contains("'''")) - { - inMultilineString = false; - } - stringBuilder.AppendLine(line); - continue; - } - if (line.Contains("'''")) - { - inMultilineString = true; - stringBuilder.AppendLine($"{indent}{line}"); - continue; - } - if (i == 0 && !indentFirstLine) - { - stringBuilder.AppendLine($"{line}"); - } - else - { - stringBuilder.AppendLine($"{indent}{line}"); - } - } - if (stringBuilder.Length == length + emptyObjectLength) - { - stringBuilder.Length = stringBuilder.Length - emptyObjectLength - formattedPropertyName.Length; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/ChangeTrackingDictionary.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/ChangeTrackingDictionary.cs deleted file mode 100644 index 3e0457dd83..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/ChangeTrackingDictionary.cs +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; - -namespace Azure.ResourceManager -{ - internal class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary where TKey : notnull - { - private IDictionary _innerDictionary; - - public ChangeTrackingDictionary() - { - } - - public ChangeTrackingDictionary(IDictionary dictionary) - { - if (dictionary == null) - { - return; - } - _innerDictionary = new Dictionary(dictionary); - } - - public ChangeTrackingDictionary(IReadOnlyDictionary dictionary) - { - if (dictionary == null) - { - return; - } - _innerDictionary = new Dictionary(); - foreach (var pair in dictionary) - { - _innerDictionary.Add(pair); - } - } - - public bool IsUndefined => _innerDictionary == null; - - public int Count => IsUndefined ? 0 : EnsureDictionary().Count; - - public bool IsReadOnly => IsUndefined ? false : EnsureDictionary().IsReadOnly; - - public ICollection Keys => IsUndefined ? Array.Empty() : EnsureDictionary().Keys; - - public ICollection Values => IsUndefined ? Array.Empty() : EnsureDictionary().Values; - - public TValue this[TKey key] - { - get - { - if (IsUndefined) - { - throw new KeyNotFoundException(nameof(key)); - } - return EnsureDictionary()[key]; - } - set - { - EnsureDictionary()[key] = value; - } - } - - IEnumerable IReadOnlyDictionary.Keys => Keys; - - IEnumerable IReadOnlyDictionary.Values => Values; - - public IEnumerator> GetEnumerator() - { - if (IsUndefined) - { - IEnumerator> enumerateEmpty() - { - yield break; - } - return enumerateEmpty(); - } - return EnsureDictionary().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - public void Add(KeyValuePair item) - { - EnsureDictionary().Add(item); - } - - public void Clear() - { - EnsureDictionary().Clear(); - } - - public bool Contains(KeyValuePair item) - { - if (IsUndefined) - { - return false; - } - return EnsureDictionary().Contains(item); - } - - public void CopyTo(KeyValuePair[] array, int index) - { - if (IsUndefined) - { - return; - } - EnsureDictionary().CopyTo(array, index); - } - - public bool Remove(KeyValuePair item) - { - if (IsUndefined) - { - return false; - } - return EnsureDictionary().Remove(item); - } - - public void Add(TKey key, TValue value) - { - EnsureDictionary().Add(key, value); - } - - public bool ContainsKey(TKey key) - { - if (IsUndefined) - { - return false; - } - return EnsureDictionary().ContainsKey(key); - } - - public bool Remove(TKey key) - { - if (IsUndefined) - { - return false; - } - return EnsureDictionary().Remove(key); - } - - public bool TryGetValue(TKey key, out TValue value) - { - if (IsUndefined) - { - value = default; - return false; - } - return EnsureDictionary().TryGetValue(key, out value); - } - - public IDictionary EnsureDictionary() - { - return _innerDictionary ??= new Dictionary(); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/ChangeTrackingList.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/ChangeTrackingList.cs deleted file mode 100644 index 1837046c52..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/ChangeTrackingList.cs +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; - -namespace Azure.ResourceManager -{ - internal class ChangeTrackingList : IList, IReadOnlyList - { - private IList _innerList; - - public ChangeTrackingList() - { - } - - public ChangeTrackingList(IList innerList) - { - if (innerList != null) - { - _innerList = innerList; - } - } - - public ChangeTrackingList(IReadOnlyList innerList) - { - if (innerList != null) - { - _innerList = innerList.ToList(); - } - } - - public bool IsUndefined => _innerList == null; - - public int Count => IsUndefined ? 0 : EnsureList().Count; - - public bool IsReadOnly => IsUndefined ? false : EnsureList().IsReadOnly; - - public T this[int index] - { - get - { - if (IsUndefined) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - return EnsureList()[index]; - } - set - { - if (IsUndefined) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - EnsureList()[index] = value; - } - } - - public void Reset() - { - _innerList = null; - } - - public IEnumerator GetEnumerator() - { - if (IsUndefined) - { - IEnumerator enumerateEmpty() - { - yield break; - } - return enumerateEmpty(); - } - return EnsureList().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - public void Add(T item) - { - EnsureList().Add(item); - } - - public void Clear() - { - EnsureList().Clear(); - } - - public bool Contains(T item) - { - if (IsUndefined) - { - return false; - } - return EnsureList().Contains(item); - } - - public void CopyTo(T[] array, int arrayIndex) - { - if (IsUndefined) - { - return; - } - EnsureList().CopyTo(array, arrayIndex); - } - - public bool Remove(T item) - { - if (IsUndefined) - { - return false; - } - return EnsureList().Remove(item); - } - - public int IndexOf(T item) - { - if (IsUndefined) - { - return -1; - } - return EnsureList().IndexOf(item); - } - - public void Insert(int index, T item) - { - EnsureList().Insert(index, item); - } - - public void RemoveAt(int index) - { - if (IsUndefined) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - EnsureList().RemoveAt(index); - } - - public IList EnsureList() - { - return _innerList ??= new List(); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/ModelSerializationExtensions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/ModelSerializationExtensions.cs deleted file mode 100644 index c879f184e7..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/ModelSerializationExtensions.cs +++ /dev/null @@ -1,407 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.Text.Json; -using System.Xml; -using Azure.Core; - -namespace Azure.ResourceManager -{ - internal static class ModelSerializationExtensions - { - internal static readonly JsonDocumentOptions JsonDocumentOptions = new JsonDocumentOptions { MaxDepth = 256 }; - internal static readonly ModelReaderWriterOptions WireOptions = new ModelReaderWriterOptions("W"); - internal static readonly BinaryData SentinelValue = BinaryData.FromBytes("\"__EMPTY__\""u8.ToArray()); - - public static object GetObject(this JsonElement element) - { - switch (element.ValueKind) - { - case JsonValueKind.String: - return element.GetString(); - case JsonValueKind.Number: - if (element.TryGetInt32(out int intValue)) - { - return intValue; - } - if (element.TryGetInt64(out long longValue)) - { - return longValue; - } - return element.GetDouble(); - case JsonValueKind.True: - return true; - case JsonValueKind.False: - return false; - case JsonValueKind.Undefined: - case JsonValueKind.Null: - return null; - case JsonValueKind.Object: - var dictionary = new Dictionary(); - foreach (var jsonProperty in element.EnumerateObject()) - { - dictionary.Add(jsonProperty.Name, jsonProperty.Value.GetObject()); - } - return dictionary; - case JsonValueKind.Array: - var list = new List(); - foreach (var item in element.EnumerateArray()) - { - list.Add(item.GetObject()); - } - return list.ToArray(); - default: - throw new NotSupportedException($"Not supported value kind {element.ValueKind}"); - } - } - - public static byte[] GetBytesFromBase64(this JsonElement element, string format) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - - return format switch - { - "U" => TypeFormatters.FromBase64UrlString(element.GetRequiredString()), - "D" => element.GetBytesFromBase64(), - _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) - }; - } - - public static DateTimeOffset GetDateTimeOffset(this JsonElement element, string format) => format switch - { - "U" when element.ValueKind == JsonValueKind.Number => DateTimeOffset.FromUnixTimeSeconds(element.GetInt64()), - _ => TypeFormatters.ParseDateTimeOffset(element.GetString(), format) - }; - - public static TimeSpan GetTimeSpan(this JsonElement element, string format) => TypeFormatters.ParseTimeSpan(element.GetString(), format); - - public static char GetChar(this JsonElement element) - { - if (element.ValueKind == JsonValueKind.String) - { - var text = element.GetString(); - if (text == null || text.Length != 1) - { - throw new NotSupportedException($"Cannot convert \"{text}\" to a char"); - } - return text[0]; - } - else - { - throw new NotSupportedException($"Cannot convert {element.ValueKind} to a char"); - } - } - - [Conditional("DEBUG")] - public static void ThrowNonNullablePropertyIsNull(this JsonProperty property) - { - throw new JsonException($"A property '{property.Name}' defined as non-nullable but received as null from the service. This exception only happens in DEBUG builds of the library and would be ignored in the release build"); - } - - public static string GetRequiredString(this JsonElement element) - { - var value = element.GetString(); - if (value == null) - { - throw new InvalidOperationException($"The requested operation requires an element of type 'String', but the target element has type '{element.ValueKind}'."); - } - return value; - } - - public static void WriteStringValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) - { - writer.WriteStringValue(TypeFormatters.ToString(value, format)); - } - - public static void WriteStringValue(this Utf8JsonWriter writer, DateTime value, string format) - { - writer.WriteStringValue(TypeFormatters.ToString(value, format)); - } - - public static void WriteStringValue(this Utf8JsonWriter writer, TimeSpan value, string format) - { - writer.WriteStringValue(TypeFormatters.ToString(value, format)); - } - - public static void WriteStringValue(this Utf8JsonWriter writer, char value) - { - writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture)); - } - - public static void WriteBase64StringValue(this Utf8JsonWriter writer, byte[] value, string format) - { - if (value == null) - { - writer.WriteNullValue(); - return; - } - switch (format) - { - case "U": - writer.WriteStringValue(TypeFormatters.ToBase64UrlString(value)); - break; - case "D": - writer.WriteBase64StringValue(value); - break; - default: - throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)); - } - } - - public static void WriteNumberValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) - { - if (format != "U") - { - throw new ArgumentOutOfRangeException(nameof(format), "Only 'U' format is supported when writing a DateTimeOffset as a Number."); - } - writer.WriteNumberValue(value.ToUnixTimeSeconds()); - } - - public static void WriteObjectValue(this Utf8JsonWriter writer, T value, ModelReaderWriterOptions options = null) - { - switch (value) - { - case null: - writer.WriteNullValue(); - break; - case IJsonModel jsonModel: - jsonModel.Write(writer, options ?? WireOptions); - break; - case IUtf8JsonSerializable serializable: - serializable.Write(writer); - break; - case byte[] bytes: - writer.WriteBase64StringValue(bytes); - break; - case BinaryData bytes0: - writer.WriteBase64StringValue(bytes0); - break; - case JsonElement json: - json.WriteTo(writer); - break; - case int i: - writer.WriteNumberValue(i); - break; - case decimal d: - writer.WriteNumberValue(d); - break; - case double d0: - if (double.IsNaN(d0)) - { - writer.WriteStringValue("NaN"); - } - else - { - writer.WriteNumberValue(d0); - } - break; - case float f: - writer.WriteNumberValue(f); - break; - case long l: - writer.WriteNumberValue(l); - break; - case string s: - writer.WriteStringValue(s); - break; - case bool b: - writer.WriteBooleanValue(b); - break; - case Guid g: - writer.WriteStringValue(g); - break; - case DateTimeOffset dateTimeOffset: - writer.WriteStringValue(dateTimeOffset, "O"); - break; - case DateTime dateTime: - writer.WriteStringValue(dateTime, "O"); - break; - case IEnumerable> enumerable: - writer.WriteStartObject(); - foreach (var pair in enumerable) - { - writer.WritePropertyName(pair.Key); - writer.WriteObjectValue(pair.Value, options); - } - writer.WriteEndObject(); - break; - case IEnumerable objectEnumerable: - writer.WriteStartArray(); - foreach (var item in objectEnumerable) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - break; - case TimeSpan timeSpan: - writer.WriteStringValue(timeSpan, "P"); - break; - default: - throw new NotSupportedException($"Not supported type {value.GetType()}"); - } - } - - public static void WriteObjectValue(this Utf8JsonWriter writer, object value, ModelReaderWriterOptions options = null) - { - writer.WriteObjectValue(value, options); - } - - internal static bool IsSentinelValue(BinaryData value) - { - ReadOnlySpan sentinelSpan = SentinelValue.ToMemory().Span; - ReadOnlySpan valueSpan = value.ToMemory().Span; - return sentinelSpan.SequenceEqual(valueSpan); - } - - internal static class TypeFormatters - { - private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; - public const string DefaultNumberFormat = "G"; - - public static string ToString(bool value) => value ? "true" : "false"; - - public static string ToString(DateTime value, string format) => value.Kind switch - { - DateTimeKind.Utc => ToString((DateTimeOffset)value, format), - _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Azure SDK requires it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") - }; - - public static string ToString(DateTimeOffset value, string format) => format switch - { - "D" => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), - "U" => value.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), - "O" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), - "o" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), - "R" => value.ToString("r", CultureInfo.InvariantCulture), - _ => value.ToString(format, CultureInfo.InvariantCulture) - }; - - public static string ToString(TimeSpan value, string format) => format switch - { - "P" => XmlConvert.ToString(value), - _ => value.ToString(format, CultureInfo.InvariantCulture) - }; - - public static string ToString(byte[] value, string format) => format switch - { - "U" => ToBase64UrlString(value), - "D" => Convert.ToBase64String(value), - _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) - }; - - public static string ToBase64UrlString(byte[] value) - { - int numWholeOrPartialInputBlocks = checked(value.Length + 2) / 3; - int size = checked(numWholeOrPartialInputBlocks * 4); - char[] output = new char[size]; - - int numBase64Chars = Convert.ToBase64CharArray(value, 0, value.Length, output, 0); - - int i = 0; - for (; i < numBase64Chars; i++) - { - char ch = output[i]; - if (ch == '+') - { - output[i] = '-'; - } - else - { - if (ch == '/') - { - output[i] = '_'; - } - else - { - if (ch == '=') - { - break; - } - } - } - } - - return new string(output, 0, i); - } - - public static byte[] FromBase64UrlString(string value) - { - int paddingCharsToAdd = (value.Length % 4) switch - { - 0 => 0, - 2 => 2, - 3 => 1, - _ => throw new InvalidOperationException("Malformed input") - }; - char[] output = new char[(value.Length + paddingCharsToAdd)]; - int i = 0; - for (; i < value.Length; i++) - { - char ch = value[i]; - if (ch == '-') - { - output[i] = '+'; - } - else - { - if (ch == '_') - { - output[i] = '/'; - } - else - { - output[i] = ch; - } - } - } - - for (; i < output.Length; i++) - { - output[i] = '='; - } - - return Convert.FromBase64CharArray(output, 0, output.Length); - } - - public static DateTimeOffset ParseDateTimeOffset(string value, string format) => format switch - { - "U" => DateTimeOffset.FromUnixTimeSeconds(long.Parse(value, CultureInfo.InvariantCulture)), - _ => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) - }; - - public static TimeSpan ParseTimeSpan(string value, string format) => format switch - { - "P" => XmlConvert.ToTimeSpan(value), - _ => TimeSpan.ParseExact(value, format, CultureInfo.InvariantCulture) - }; - - public static string ConvertToString(object value, string format = null) => value switch - { - null => "null", - string s => s, - bool b => ToString(b), - int or float or double or long or decimal => ((IFormattable)value).ToString(DefaultNumberFormat, CultureInfo.InvariantCulture), - byte[] b0 when format != null => ToString(b0, format), - IEnumerable s0 => string.Join(",", s0), - DateTimeOffset dateTime when format != null => ToString(dateTime, format), - TimeSpan timeSpan when format != null => ToString(timeSpan, format), - TimeSpan timeSpan0 => XmlConvert.ToString(timeSpan0), - Guid guid => guid.ToString(), - BinaryData binaryData => ConvertToString(binaryData.ToArray(), format), - _ => value.ToString() - }; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/Optional.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/Optional.cs deleted file mode 100644 index c21cb37eee..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/Optional.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.ResourceManager -{ - internal static class Optional - { - public static bool IsCollectionDefined(IEnumerable collection) - { - return !(collection is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined); - } - - public static bool IsCollectionDefined(IDictionary collection) - { - return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); - } - - public static bool IsCollectionDefined(IReadOnlyDictionary collection) - { - return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); - } - - public static bool IsDefined(T? value) - where T : struct - { - return value.HasValue; - } - - public static bool IsDefined(object value) - { - return value != null; - } - - public static bool IsDefined(JsonElement value) - { - return value.ValueKind != JsonValueKind.Undefined; - } - - public static bool IsDefined(string value) - { - return value != null; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/WirePathAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/WirePathAttribute.cs deleted file mode 100644 index 6a974d2a89..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Internal/WirePathAttribute.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager -{ - [AttributeUsage(AttributeTargets.Property)] - internal class WirePathAttribute : Attribute - { - private string _wirePath; - - public WirePathAttribute(string wirePath) - { - _wirePath = wirePath; - } - - public override string ToString() - { - return _wirePath; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmPlan.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmPlan.Serialization.cs deleted file mode 100644 index 95e2fd6d05..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmPlan.Serialization.cs +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - [JsonConverter(typeof(ArmPlanConverter))] - public partial class ArmPlan : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - private void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmPlan)} does not support writing '{format}' format."); - } - - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - writer.WritePropertyName("publisher"u8); - writer.WriteStringValue(Publisher); - writer.WritePropertyName("product"u8); - writer.WriteStringValue(Product); - if (Optional.IsDefined(PromotionCode)) - { - writer.WritePropertyName("promotionCode"u8); - writer.WriteStringValue(PromotionCode); - } - if (Optional.IsDefined(Version)) - { - writer.WritePropertyName("version"u8); - writer.WriteStringValue(Version); - } - } - - ArmPlan IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmPlan)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeArmPlan(document.RootElement, options); - } - - internal static ArmPlan DeserializeArmPlan(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - string publisher = default; - string product = default; - string promotionCode = default; - string version = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("publisher"u8)) - { - publisher = property.Value.GetString(); - continue; - } - if (property.NameEquals("product"u8)) - { - product = property.Value.GetString(); - continue; - } - if (property.NameEquals("promotionCode"u8)) - { - promotionCode = property.Value.GetString(); - continue; - } - if (property.NameEquals("version"u8)) - { - version = property.Value.GetString(); - continue; - } - } - return new ArmPlan(name, publisher, product, promotionCode, version); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Publisher), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" publisher: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Publisher)) - { - builder.Append(" publisher: "); - if (Publisher.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Publisher}'''"); - } - else - { - builder.AppendLine($"'{Publisher}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Product), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" product: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Product)) - { - builder.Append(" product: "); - if (Product.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Product}'''"); - } - else - { - builder.AppendLine($"'{Product}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PromotionCode), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" promotionCode: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PromotionCode)) - { - builder.Append(" promotionCode: "); - if (PromotionCode.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{PromotionCode}'''"); - } - else - { - builder.AppendLine($"'{PromotionCode}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Version), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" version: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Version)) - { - builder.Append(" version: "); - if (Version.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Version}'''"); - } - else - { - builder.AppendLine($"'{Version}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ArmPlan)} does not support writing '{options.Format}' format."); - } - } - - ArmPlan IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeArmPlan(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ArmPlan)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class ArmPlanConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, ArmPlan model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model, ModelSerializationExtensions.WireOptions); - } - - public override ArmPlan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeArmPlan(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmPlan.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmPlan.cs deleted file mode 100644 index 711ac5f348..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmPlan.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// Plan for the resource. - [PropertyReferenceType] - public partial class ArmPlan - { - /// Initializes a new instance of . - /// A user defined name of the 3rd Party Artifact that is being procured. - /// The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic. - /// The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to the OfferID specified for the artifact at the time of Data Market onboarding. - /// , or is null. - [InitializationConstructor] - public ArmPlan(string name, string publisher, string product) - { - Argument.AssertNotNull(name, nameof(name)); - Argument.AssertNotNull(publisher, nameof(publisher)); - Argument.AssertNotNull(product, nameof(product)); - - Name = name; - Publisher = publisher; - Product = product; - } - - /// Initializes a new instance of . - /// A user defined name of the 3rd Party Artifact that is being procured. - /// The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic. - /// The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to the OfferID specified for the artifact at the time of Data Market onboarding. - /// A publisher provided promotion code as provisioned in Data Market for the said product/artifact. - /// The version of the desired product/artifact. - [SerializationConstructor] - internal ArmPlan(string name, string publisher, string product, string promotionCode, string version) - { - Name = name; - Publisher = publisher; - Product = product; - PromotionCode = promotionCode; - Version = version; - } - - /// Initializes a new instance of for deserialization. - internal ArmPlan() - { - } - - /// A user defined name of the 3rd Party Artifact that is being procured. - [WirePath("name")] - public string Name { get; set; } - /// The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic. - [WirePath("publisher")] - public string Publisher { get; set; } - /// The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to the OfferID specified for the artifact at the time of Data Market onboarding. - [WirePath("product")] - public string Product { get; set; } - /// A publisher provided promotion code as provisioned in Data Market for the said product/artifact. - [WirePath("promotionCode")] - public string PromotionCode { get; set; } - /// The version of the desired product/artifact. - [WirePath("version")] - public string Version { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmSku.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmSku.Serialization.cs deleted file mode 100644 index ee12d1ffab..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmSku.Serialization.cs +++ /dev/null @@ -1,289 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - [JsonConverter(typeof(ArmSkuConverter))] - public partial class ArmSku : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - private void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmSku)} does not support writing '{format}' format."); - } - - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - if (Optional.IsDefined(Tier)) - { - writer.WritePropertyName("tier"u8); - writer.WriteStringValue(Tier.Value.ToSerialString()); - } - if (Optional.IsDefined(Size)) - { - writer.WritePropertyName("size"u8); - writer.WriteStringValue(Size); - } - if (Optional.IsDefined(Family)) - { - writer.WritePropertyName("family"u8); - writer.WriteStringValue(Family); - } - if (Optional.IsDefined(Capacity)) - { - writer.WritePropertyName("capacity"u8); - writer.WriteNumberValue(Capacity.Value); - } - } - - ArmSku IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmSku)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeArmSku(document.RootElement, options); - } - - internal static ArmSku DeserializeArmSku(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - ArmSkuTier? tier = default; - string size = default; - string family = default; - int? capacity = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("tier"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - tier = property.Value.GetString().ToArmSkuTier(); - continue; - } - if (property.NameEquals("size"u8)) - { - size = property.Value.GetString(); - continue; - } - if (property.NameEquals("family"u8)) - { - family = property.Value.GetString(); - continue; - } - if (property.NameEquals("capacity"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - capacity = property.Value.GetInt32(); - continue; - } - } - return new ArmSku(name, tier, size, family, capacity); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Tier), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tier: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Tier)) - { - builder.Append(" tier: "); - builder.AppendLine($"'{Tier.Value.ToSerialString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Size), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" size: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Size)) - { - builder.Append(" size: "); - if (Size.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Size}'''"); - } - else - { - builder.AppendLine($"'{Size}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Family), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" family: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Family)) - { - builder.Append(" family: "); - if (Family.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Family}'''"); - } - else - { - builder.AppendLine($"'{Family}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Capacity), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" capacity: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Capacity)) - { - builder.Append(" capacity: "); - builder.AppendLine($"{Capacity.Value}"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ArmSku)} does not support writing '{options.Format}' format."); - } - } - - ArmSku IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeArmSku(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ArmSku)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class ArmSkuConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, ArmSku model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model, ModelSerializationExtensions.WireOptions); - } - - public override ArmSku Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeArmSku(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmSku.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmSku.cs deleted file mode 100644 index 4a4de3ba03..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmSku.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// The resource model definition representing SKU. - [PropertyReferenceType] - public partial class ArmSku - { - /// Initializes a new instance of . - /// The name of the SKU. Ex - P3. It is typically a letter+number code. - /// is null. - [InitializationConstructor] - public ArmSku(string name) - { - Argument.AssertNotNull(name, nameof(name)); - - Name = name; - } - - /// Initializes a new instance of . - /// The name of the SKU. Ex - P3. It is typically a letter+number code. - /// This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required on a PUT. - /// The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. - /// If the service has different generations of hardware, for the same SKU, then that can be captured here. - /// If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the resource this may be omitted. - [SerializationConstructor] - internal ArmSku(string name, ArmSkuTier? tier, string size, string family, int? capacity) - { - Name = name; - Tier = tier; - Size = size; - Family = family; - Capacity = capacity; - } - - /// Initializes a new instance of for deserialization. - internal ArmSku() - { - } - - /// The name of the SKU. Ex - P3. It is typically a letter+number code. - [WirePath("name")] - public string Name { get; set; } - /// This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required on a PUT. - [WirePath("tier")] - public ArmSkuTier? Tier { get; set; } - /// The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. - [WirePath("size")] - public string Size { get; set; } - /// If the service has different generations of hardware, for the same SKU, then that can be captured here. - [WirePath("family")] - public string Family { get; set; } - /// If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the resource this may be omitted. - [WirePath("capacity")] - public int? Capacity { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmSkuTier.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmSkuTier.Serialization.cs deleted file mode 100644 index c640e16a48..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmSkuTier.Serialization.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.Models -{ - internal static partial class ArmSkuTierExtensions - { - public static string ToSerialString(this ArmSkuTier value) => value switch - { - ArmSkuTier.Free => "Free", - ArmSkuTier.Basic => "Basic", - ArmSkuTier.Standard => "Standard", - ArmSkuTier.Premium => "Premium", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ArmSkuTier value.") - }; - - public static ArmSkuTier ToArmSkuTier(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Free")) return ArmSkuTier.Free; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Basic")) return ArmSkuTier.Basic; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Standard")) return ArmSkuTier.Standard; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Premium")) return ArmSkuTier.Premium; - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ArmSkuTier value."); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmSkuTier.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmSkuTier.cs deleted file mode 100644 index 4320a2d3b4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ArmSkuTier.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.Models -{ - /// This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required on a PUT. - public enum ArmSkuTier - { - /// Free. - Free, - /// Basic. - Basic, - /// Standard. - Standard, - /// Premium. - Premium - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/AzureResourceManagerContext.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/AzureResourceManagerContext.cs deleted file mode 100644 index f26fee2f3a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/AzureResourceManagerContext.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.ClientModel.Primitives; - -namespace Azure.ResourceManager -{ - /// - /// Context class which will be filled in by the System.ClientModel.SourceGeneration. - /// For more information see 'https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/System.ClientModel/src/docs/ModelReaderWriterContext.md' - /// - public partial class AzureResourceManagerContext : ModelReaderWriterContext - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/CreatedByType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/CreatedByType.cs deleted file mode 100644 index f7a4c34f58..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/CreatedByType.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Models -{ - /// The type of identity that created the resource. - public readonly partial struct CreatedByType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public CreatedByType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string UserValue = "User"; - private const string ApplicationValue = "Application"; - private const string ManagedIdentityValue = "ManagedIdentity"; - private const string KeyValue = "Key"; - - /// User. - public static CreatedByType User { get; } = new CreatedByType(UserValue); - /// Application. - public static CreatedByType Application { get; } = new CreatedByType(ApplicationValue); - /// ManagedIdentity. - public static CreatedByType ManagedIdentity { get; } = new CreatedByType(ManagedIdentityValue); - /// Key. - public static CreatedByType Key { get; } = new CreatedByType(KeyValue); - /// Determines if two values are the same. - public static bool operator ==(CreatedByType left, CreatedByType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(CreatedByType left, CreatedByType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator CreatedByType(string value) => new CreatedByType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is CreatedByType other && Equals(other); - /// - public bool Equals(CreatedByType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/EncryptionProperties.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/EncryptionProperties.Serialization.cs deleted file mode 100644 index bc9ff0979a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/EncryptionProperties.Serialization.cs +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - [JsonConverter(typeof(EncryptionPropertiesConverter))] - public partial class EncryptionProperties : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(EncryptionProperties)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Status)) - { - writer.WritePropertyName("status"u8); - writer.WriteStringValue(Status.Value.ToString()); - } - if (Optional.IsDefined(KeyVaultProperties)) - { - writer.WritePropertyName("keyVaultProperties"u8); - writer.WriteObjectValue(KeyVaultProperties, options); - } - } - - EncryptionProperties IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(EncryptionProperties)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeEncryptionProperties(document.RootElement, options); - } - - internal static EncryptionProperties DeserializeEncryptionProperties(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - EncryptionStatus? status = default; - KeyVaultProperties keyVaultProperties = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("status"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - status = new EncryptionStatus(property.Value.GetString()); - continue; - } - if (property.NameEquals("keyVaultProperties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - keyVaultProperties = KeyVaultProperties.DeserializeKeyVaultProperties(property.Value, options); - continue; - } - } - return new EncryptionProperties(status, keyVaultProperties); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Status), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" status: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Status)) - { - builder.Append(" status: "); - builder.AppendLine($"'{Status.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(KeyVaultProperties), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" keyVaultProperties: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(KeyVaultProperties)) - { - builder.Append(" keyVaultProperties: "); - BicepSerializationHelpers.AppendChildObject(builder, KeyVaultProperties, options, 2, false, " keyVaultProperties: "); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(EncryptionProperties)} does not support writing '{options.Format}' format."); - } - } - - EncryptionProperties IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeEncryptionProperties(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(EncryptionProperties)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class EncryptionPropertiesConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, EncryptionProperties model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model, ModelSerializationExtensions.WireOptions); - } - - public override EncryptionProperties Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeEncryptionProperties(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/EncryptionProperties.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/EncryptionProperties.cs deleted file mode 100644 index 5b441bcc81..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/EncryptionProperties.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// Configuration of key for data encryption. - [PropertyReferenceType] - public partial class EncryptionProperties - { - /// Initializes a new instance of . - [InitializationConstructor] - public EncryptionProperties() - { - } - - /// Initializes a new instance of . - /// Indicates whether or not the encryption is enabled for container registry. - /// Key vault properties. - [SerializationConstructor] - internal EncryptionProperties(EncryptionStatus? status, KeyVaultProperties keyVaultProperties) - { - Status = status; - KeyVaultProperties = keyVaultProperties; - } - - /// Indicates whether or not the encryption is enabled for container registry. - [WirePath("status")] - public EncryptionStatus? Status { get; set; } - /// Key vault properties. - [WirePath("keyVaultProperties")] - public KeyVaultProperties KeyVaultProperties { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/EncryptionStatus.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/EncryptionStatus.cs deleted file mode 100644 index c69242b97c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/EncryptionStatus.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Models -{ - /// Indicates whether or not the encryption is enabled for container registry. - public readonly partial struct EncryptionStatus : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public EncryptionStatus(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string EnabledValue = "enabled"; - private const string DisabledValue = "disabled"; - - /// enabled. - public static EncryptionStatus Enabled { get; } = new EncryptionStatus(EnabledValue); - /// disabled. - public static EncryptionStatus Disabled { get; } = new EncryptionStatus(DisabledValue); - /// Determines if two values are the same. - public static bool operator ==(EncryptionStatus left, EncryptionStatus right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(EncryptionStatus left, EncryptionStatus right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator EncryptionStatus(string value) => new EncryptionStatus(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is EncryptionStatus other && Equals(other); - /// - public bool Equals(EncryptionStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/KeyVaultProperties.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/KeyVaultProperties.Serialization.cs deleted file mode 100644 index 5280cd7b90..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/KeyVaultProperties.Serialization.cs +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - [JsonConverter(typeof(KeyVaultPropertiesConverter))] - public partial class KeyVaultProperties : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(KeyVaultProperties)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(KeyIdentifier)) - { - writer.WritePropertyName("keyIdentifier"u8); - writer.WriteStringValue(KeyIdentifier); - } - if (Optional.IsDefined(Identity)) - { - writer.WritePropertyName("identity"u8); - writer.WriteStringValue(Identity); - } - } - - KeyVaultProperties IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(KeyVaultProperties)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeKeyVaultProperties(document.RootElement, options); - } - - internal static KeyVaultProperties DeserializeKeyVaultProperties(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string keyIdentifier = default; - string identity = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("keyIdentifier"u8)) - { - keyIdentifier = property.Value.GetString(); - continue; - } - if (property.NameEquals("identity"u8)) - { - identity = property.Value.GetString(); - continue; - } - } - return new KeyVaultProperties(keyIdentifier, identity); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(KeyIdentifier), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" keyIdentifier: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(KeyIdentifier)) - { - builder.Append(" keyIdentifier: "); - if (KeyIdentifier.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{KeyIdentifier}'''"); - } - else - { - builder.AppendLine($"'{KeyIdentifier}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Identity), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" identity: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Identity)) - { - builder.Append(" identity: "); - if (Identity.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Identity}'''"); - } - else - { - builder.AppendLine($"'{Identity}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(KeyVaultProperties)} does not support writing '{options.Format}' format."); - } - } - - KeyVaultProperties IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeKeyVaultProperties(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(KeyVaultProperties)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class KeyVaultPropertiesConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, KeyVaultProperties model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model, ModelSerializationExtensions.WireOptions); - } - - public override KeyVaultProperties Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeKeyVaultProperties(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/KeyVaultProperties.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/KeyVaultProperties.cs deleted file mode 100644 index 2e92a30cff..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/KeyVaultProperties.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// The KeyVaultProperties. - [PropertyReferenceType] - public partial class KeyVaultProperties - { - /// Initializes a new instance of . - [InitializationConstructor] - public KeyVaultProperties() - { - } - - /// Initializes a new instance of . - /// Key vault uri to access the encryption key. - /// The client ID of the identity which will be used to access key vault. - [SerializationConstructor] - internal KeyVaultProperties(string keyIdentifier, string identity) - { - KeyIdentifier = keyIdentifier; - Identity = identity; - } - - /// Key vault uri to access the encryption key. - [WirePath("keyIdentifier")] - public string KeyIdentifier { get; set; } - /// The client ID of the identity which will be used to access key vault. - [WirePath("identity")] - public string Identity { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ManagedServiceIdentityType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ManagedServiceIdentityType.cs deleted file mode 100644 index 826953ce1c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ManagedServiceIdentityType.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Models -{ - /// Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). - public readonly partial struct ManagedServiceIdentityType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ManagedServiceIdentityType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string NoneValue = "None"; - private const string SystemAssignedValue = "SystemAssigned"; - private const string UserAssignedValue = "UserAssigned"; - private const string SystemAssignedUserAssignedValue = "SystemAssigned, UserAssigned"; - - /// None. - public static ManagedServiceIdentityType None { get; } = new ManagedServiceIdentityType(NoneValue); - /// SystemAssigned. - public static ManagedServiceIdentityType SystemAssigned { get; } = new ManagedServiceIdentityType(SystemAssignedValue); - /// UserAssigned. - public static ManagedServiceIdentityType UserAssigned { get; } = new ManagedServiceIdentityType(UserAssignedValue); - /// SystemAssigned, UserAssigned. - public static ManagedServiceIdentityType SystemAssignedUserAssigned { get; } = new ManagedServiceIdentityType(SystemAssignedUserAssignedValue); - /// Determines if two values are the same. - public static bool operator ==(ManagedServiceIdentityType left, ManagedServiceIdentityType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ManagedServiceIdentityType left, ManagedServiceIdentityType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ManagedServiceIdentityType(string value) => new ManagedServiceIdentityType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ManagedServiceIdentityType other && Equals(other); - /// - public bool Equals(ManagedServiceIdentityType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/OperationStatusResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/OperationStatusResult.Serialization.cs deleted file mode 100644 index 8afe4c80f4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/OperationStatusResult.Serialization.cs +++ /dev/null @@ -1,407 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - [JsonConverter(typeof(OperationStatusResultConverter))] - public partial class OperationStatusResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(OperationStatusResult)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (options.Format != "W") - { - writer.WritePropertyName("status"u8); - writer.WriteStringValue(Status); - } - if (options.Format != "W" && Optional.IsDefined(PercentComplete)) - { - writer.WritePropertyName("percentComplete"u8); - writer.WriteNumberValue(PercentComplete.Value); - } - if (options.Format != "W" && Optional.IsDefined(StartOn)) - { - writer.WritePropertyName("startTime"u8); - writer.WriteStringValue(StartOn.Value, "O"); - } - if (options.Format != "W" && Optional.IsDefined(EndOn)) - { - writer.WritePropertyName("endTime"u8); - writer.WriteStringValue(EndOn.Value, "O"); - } - if (options.Format != "W" && Optional.IsCollectionDefined(Operations)) - { - writer.WritePropertyName("operations"u8); - writer.WriteStartArray(); - foreach (var item in Operations) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(Error)) - { - writer.WritePropertyName("error"u8); - JsonSerializer.Serialize(writer, Error, ResourceManagerJsonContext.Default.ResponseError); - } - } - - OperationStatusResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(OperationStatusResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeOperationStatusResult(document.RootElement, options); - } - - internal static OperationStatusResult DeserializeOperationStatusResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string name = default; - string status = default; - float? percentComplete = default; - DateTimeOffset? startTime = default; - DateTimeOffset? endTime = default; - IReadOnlyList operations = default; - ResponseError error = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("status"u8)) - { - status = property.Value.GetString(); - continue; - } - if (property.NameEquals("percentComplete"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - percentComplete = property.Value.GetSingle(); - continue; - } - if (property.NameEquals("startTime"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - startTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("endTime"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - endTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("operations"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(JsonSerializer.Deserialize(item.GetRawText(), ResourceManagerJsonContext.Default.OperationStatusResult)); - } - operations = array; - continue; - } - if (property.NameEquals("error"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - error = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.ResponseError); - continue; - } - } - return new OperationStatusResult( - id, - name, - status, - percentComplete, - startTime, - endTime, - operations ?? new ChangeTrackingList(), - error); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Status), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" status: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Status)) - { - builder.Append(" status: "); - if (Status.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Status}'''"); - } - else - { - builder.AppendLine($"'{Status}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PercentComplete), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" percentComplete: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PercentComplete)) - { - builder.Append(" percentComplete: "); - builder.AppendLine($"'{PercentComplete.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(StartOn), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" startTime: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(StartOn)) - { - builder.Append(" startTime: "); - var formattedDateTimeString = TypeFormatters.ToString(StartOn.Value, "o"); - builder.AppendLine($"'{formattedDateTimeString}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(EndOn), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" endTime: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(EndOn)) - { - builder.Append(" endTime: "); - var formattedDateTimeString = TypeFormatters.ToString(EndOn.Value, "o"); - builder.AppendLine($"'{formattedDateTimeString}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Operations), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" operations: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Operations)) - { - if (Operations.Any()) - { - builder.Append(" operations: "); - builder.AppendLine("["); - foreach (var item in Operations) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " operations: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Error), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" error: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Error)) - { - builder.Append(" error: "); - BicepSerializationHelpers.AppendChildObject(builder, Error, options, 2, false, " error: "); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(OperationStatusResult)} does not support writing '{options.Format}' format."); - } - } - - OperationStatusResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeOperationStatusResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(OperationStatusResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class OperationStatusResultConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, OperationStatusResult model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model, ModelSerializationExtensions.WireOptions); - } - - public override OperationStatusResult Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeOperationStatusResult(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/OperationStatusResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/OperationStatusResult.cs deleted file mode 100644 index 5a902c73e8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/OperationStatusResult.cs +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// The current status of an async operation. - [TypeReferenceType] - public partial class OperationStatusResult - { - /// Initializes a new instance of . - /// Operation status. - [InitializationConstructor] - public OperationStatusResult(string status) - { - Status = status; - Operations = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// Fully qualified ID for the async operation. - /// Name of the async operation. - /// Operation status. - /// Percent of the operation that is complete. - /// The start time of the operation. - /// The end time of the operation. - /// The operations list. - /// If present, details of the operation error. - [SerializationConstructor] - protected OperationStatusResult(ResourceIdentifier id, string name, string status, float? percentComplete, DateTimeOffset? startOn, DateTimeOffset? endOn, IReadOnlyList operations, ResponseError error) - { - Id = id; - Name = name; - Status = status; - PercentComplete = percentComplete; - StartOn = startOn; - EndOn = endOn; - Operations = operations; - Error = error; - } - - /// Initializes a new instance of for deserialization. - protected OperationStatusResult() - { - } - - /// Fully qualified ID for the async operation. - [WirePath("id")] - public ResourceIdentifier Id { get; } - /// Name of the async operation. - [WirePath("name")] - public string Name { get; } - /// Operation status. - [WirePath("status")] - public string Status { get; } - /// Percent of the operation that is complete. - [WirePath("percentComplete")] - public float? PercentComplete { get; } - /// The start time of the operation. - [WirePath("startTime")] - public DateTimeOffset? StartOn { get; } - /// The end time of the operation. - [WirePath("endTime")] - public DateTimeOffset? EndOn { get; } - /// The operations list. - [WirePath("operations")] - public IReadOnlyList Operations { get; } - /// If present, details of the operation error. - [WirePath("error")] - public ResponseError Error { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ResourceData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ResourceData.Serialization.cs deleted file mode 100644 index 1b659410bc..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ResourceData.Serialization.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Models -{ - public partial class ResourceData - { - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (options.Format != "W") - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ResourceType); - } - if (options.Format != "W" && Optional.IsDefined(SystemData)) - { - writer.WritePropertyName("systemData"u8); - writer.WriteObjectValue(SystemData, options); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ResourceData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ResourceData.cs deleted file mode 100644 index 841b931f44..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/ResourceData.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// Common fields that are returned in the response for all Azure Resource Manager resources. - [ReferenceType(new string[] { "SystemData" })] - public abstract partial class ResourceData - { - /// Initializes a new instance of . - [InitializationConstructor] - protected ResourceData() - { - } - - /// Initializes a new instance of . - /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - /// The name of the resource. - /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". - /// Azure Resource Manager metadata containing createdBy and modifiedBy information. - [SerializationConstructor] - protected ResourceData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData) - { - Id = id; - Name = name; - ResourceType = resourceType; - SystemData = systemData; - } - - /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - public ResourceIdentifier Id { get; } - /// The name of the resource. - public string Name { get; } - /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". - public ResourceType ResourceType { get; } - /// Azure Resource Manager metadata containing createdBy and modifiedBy information. - public SystemData SystemData { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentity.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentity.Serialization.cs deleted file mode 100644 index 2e420c90b8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentity.Serialization.cs +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - [JsonConverter(typeof(SystemAssignedServiceIdentityConverter))] - public partial class SystemAssignedServiceIdentity : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SystemAssignedServiceIdentity)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(PrincipalId)) - { - writer.WritePropertyName("principalId"u8); - writer.WriteStringValue(PrincipalId.Value); - } - if (options.Format != "W" && Optional.IsDefined(TenantId)) - { - writer.WritePropertyName("tenantId"u8); - writer.WriteStringValue(TenantId.Value); - } - writer.WritePropertyName("type"u8); - writer.WriteStringValue(SystemAssignedServiceIdentityType.ToString()); - } - - SystemAssignedServiceIdentity IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SystemAssignedServiceIdentity)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeSystemAssignedServiceIdentity(document.RootElement, options); - } - - internal static SystemAssignedServiceIdentity DeserializeSystemAssignedServiceIdentity(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - Guid? principalId = default; - Guid? tenantId = default; - SystemAssignedServiceIdentityType type = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("principalId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - principalId = property.Value.GetGuid(); - continue; - } - if (property.NameEquals("tenantId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - tenantId = property.Value.GetGuid(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new SystemAssignedServiceIdentityType(property.Value.GetString()); - continue; - } - } - return new SystemAssignedServiceIdentity(principalId, tenantId, type); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PrincipalId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" principalId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PrincipalId)) - { - builder.Append(" principalId: "); - builder.AppendLine($"'{PrincipalId.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TenantId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenantId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TenantId)) - { - builder.Append(" tenantId: "); - builder.AppendLine($"'{TenantId.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemAssignedServiceIdentityType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" type: "); - builder.AppendLine(propertyOverride); - } - else - { - builder.Append(" type: "); - builder.AppendLine($"'{SystemAssignedServiceIdentityType.ToString()}'"); - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(SystemAssignedServiceIdentity)} does not support writing '{options.Format}' format."); - } - } - - SystemAssignedServiceIdentity IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeSystemAssignedServiceIdentity(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(SystemAssignedServiceIdentity)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class SystemAssignedServiceIdentityConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, SystemAssignedServiceIdentity model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model, ModelSerializationExtensions.WireOptions); - } - - public override SystemAssignedServiceIdentity Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeSystemAssignedServiceIdentity(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentity.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentity.cs deleted file mode 100644 index f7feea87c2..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentity.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// Managed service identity (either system assigned, or none). - [PropertyReferenceType] - public partial class SystemAssignedServiceIdentity - { - /// Initializes a new instance of for deserialization. - internal SystemAssignedServiceIdentity() - { - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentityType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentityType.cs deleted file mode 100644 index ab44e79a42..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentityType.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Models -{ - /// Type of managed service identity (either system assigned, or none). - public readonly partial struct SystemAssignedServiceIdentityType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public SystemAssignedServiceIdentityType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string NoneValue = "None"; - private const string SystemAssignedValue = "SystemAssigned"; - - /// None. - public static SystemAssignedServiceIdentityType None { get; } = new SystemAssignedServiceIdentityType(NoneValue); - /// SystemAssigned. - public static SystemAssignedServiceIdentityType SystemAssigned { get; } = new SystemAssignedServiceIdentityType(SystemAssignedValue); - /// Determines if two values are the same. - public static bool operator ==(SystemAssignedServiceIdentityType left, SystemAssignedServiceIdentityType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(SystemAssignedServiceIdentityType left, SystemAssignedServiceIdentityType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator SystemAssignedServiceIdentityType(string value) => new SystemAssignedServiceIdentityType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is SystemAssignedServiceIdentityType other && Equals(other); - /// - public bool Equals(SystemAssignedServiceIdentityType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemData.Serialization.cs deleted file mode 100644 index 513fa91320..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemData.Serialization.cs +++ /dev/null @@ -1,326 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - [JsonConverter(typeof(SystemDataConverter))] - public partial class SystemData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SystemData)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(CreatedBy)) - { - writer.WritePropertyName("createdBy"u8); - writer.WriteStringValue(CreatedBy); - } - if (options.Format != "W" && Optional.IsDefined(CreatedByType)) - { - writer.WritePropertyName("createdByType"u8); - writer.WriteStringValue(CreatedByType.Value.ToString()); - } - if (options.Format != "W" && Optional.IsDefined(CreatedOn)) - { - writer.WritePropertyName("createdAt"u8); - writer.WriteStringValue(CreatedOn.Value, "O"); - } - if (options.Format != "W" && Optional.IsDefined(LastModifiedBy)) - { - writer.WritePropertyName("lastModifiedBy"u8); - writer.WriteStringValue(LastModifiedBy); - } - if (options.Format != "W" && Optional.IsDefined(LastModifiedByType)) - { - writer.WritePropertyName("lastModifiedByType"u8); - writer.WriteStringValue(LastModifiedByType.Value.ToString()); - } - if (options.Format != "W" && Optional.IsDefined(LastModifiedOn)) - { - writer.WritePropertyName("lastModifiedAt"u8); - writer.WriteStringValue(LastModifiedOn.Value, "O"); - } - } - - SystemData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SystemData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeSystemData(document.RootElement, options); - } - - internal static SystemData DeserializeSystemData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string createdBy = default; - CreatedByType? createdByType = default; - DateTimeOffset? createdAt = default; - string lastModifiedBy = default; - CreatedByType? lastModifiedByType = default; - DateTimeOffset? lastModifiedAt = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("createdBy"u8)) - { - createdBy = property.Value.GetString(); - continue; - } - if (property.NameEquals("createdByType"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - createdByType = new CreatedByType(property.Value.GetString()); - continue; - } - if (property.NameEquals("createdAt"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - createdAt = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("lastModifiedBy"u8)) - { - lastModifiedBy = property.Value.GetString(); - continue; - } - if (property.NameEquals("lastModifiedByType"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - lastModifiedByType = new CreatedByType(property.Value.GetString()); - continue; - } - if (property.NameEquals("lastModifiedAt"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - lastModifiedAt = property.Value.GetDateTimeOffset("O"); - continue; - } - } - return new SystemData( - createdBy, - createdByType, - createdAt, - lastModifiedBy, - lastModifiedByType, - lastModifiedAt); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(CreatedBy), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" createdBy: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(CreatedBy)) - { - builder.Append(" createdBy: "); - if (CreatedBy.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{CreatedBy}'''"); - } - else - { - builder.AppendLine($"'{CreatedBy}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(CreatedByType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" createdByType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(CreatedByType)) - { - builder.Append(" createdByType: "); - builder.AppendLine($"'{CreatedByType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(CreatedOn), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" createdAt: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(CreatedOn)) - { - builder.Append(" createdAt: "); - var formattedDateTimeString = TypeFormatters.ToString(CreatedOn.Value, "o"); - builder.AppendLine($"'{formattedDateTimeString}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(LastModifiedBy), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" lastModifiedBy: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(LastModifiedBy)) - { - builder.Append(" lastModifiedBy: "); - if (LastModifiedBy.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{LastModifiedBy}'''"); - } - else - { - builder.AppendLine($"'{LastModifiedBy}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(LastModifiedByType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" lastModifiedByType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(LastModifiedByType)) - { - builder.Append(" lastModifiedByType: "); - builder.AppendLine($"'{LastModifiedByType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(LastModifiedOn), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" lastModifiedAt: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(LastModifiedOn)) - { - builder.Append(" lastModifiedAt: "); - var formattedDateTimeString = TypeFormatters.ToString(LastModifiedOn.Value, "o"); - builder.AppendLine($"'{formattedDateTimeString}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(SystemData)} does not support writing '{options.Format}' format."); - } - } - - SystemData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeSystemData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(SystemData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class SystemDataConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, SystemData model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model, ModelSerializationExtensions.WireOptions); - } - - public override SystemData Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeSystemData(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemData.cs deleted file mode 100644 index 14d762f3b5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/SystemData.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// Metadata pertaining to creation and last modification of the resource. - [PropertyReferenceType] - public partial class SystemData - { - /// Initializes a new instance of . - [InitializationConstructor] - public SystemData() - { - } - - /// Initializes a new instance of . - /// The identity that created the resource. - /// The type of identity that created the resource. - /// The timestamp of resource creation (UTC). - /// The identity that last modified the resource. - /// The type of identity that last modified the resource. - /// The timestamp of resource last modification (UTC). - [SerializationConstructor] - internal SystemData(string createdBy, CreatedByType? createdByType, DateTimeOffset? createdOn, string lastModifiedBy, CreatedByType? lastModifiedByType, DateTimeOffset? lastModifiedOn) - { - CreatedBy = createdBy; - CreatedByType = createdByType; - CreatedOn = createdOn; - LastModifiedBy = lastModifiedBy; - LastModifiedByType = lastModifiedByType; - LastModifiedOn = lastModifiedOn; - } - - /// The identity that created the resource. - [WirePath("createdBy")] - public string CreatedBy { get; } - /// The type of identity that created the resource. - [WirePath("createdByType")] - public CreatedByType? CreatedByType { get; } - /// The timestamp of resource creation (UTC). - [WirePath("createdAt")] - public DateTimeOffset? CreatedOn { get; } - /// The identity that last modified the resource. - [WirePath("lastModifiedBy")] - public string LastModifiedBy { get; } - /// The type of identity that last modified the resource. - [WirePath("lastModifiedByType")] - public CreatedByType? LastModifiedByType { get; } - /// The timestamp of resource last modification (UTC). - [WirePath("lastModifiedAt")] - public DateTimeOffset? LastModifiedOn { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/TrackedResourceData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/TrackedResourceData.Serialization.cs deleted file mode 100644 index a6af3ca008..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/TrackedResourceData.Serialization.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Models -{ - public partial class TrackedResourceData - { - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - base.JsonModelWriteCore(writer, options); - if (Optional.IsCollectionDefined(Tags)) - { - writer.WritePropertyName("tags"u8); - writer.WriteStartObject(); - foreach (var item in Tags) - { - writer.WritePropertyName(item.Key); - writer.WriteStringValue(item.Value); - } - writer.WriteEndObject(); - } - writer.WritePropertyName("location"u8); - writer.WriteStringValue(Location); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/TrackedResourceData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/TrackedResourceData.cs deleted file mode 100644 index 741469301d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/TrackedResourceData.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. - [ReferenceType(new string[] { "SystemData" })] - public abstract partial class TrackedResourceData : ResourceData - { - /// Initializes a new instance of . - /// The geo-location where the resource lives. - [InitializationConstructor] - protected TrackedResourceData(AzureLocation location) - { - Tags = new ChangeTrackingDictionary(); - Location = location; - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// Resource tags. - /// The geo-location where the resource lives. - [SerializationConstructor] - protected TrackedResourceData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, IDictionary tags, AzureLocation location) : base(id, name, resourceType, systemData) - { - Tags = tags; - Location = location; - } - - /// Initializes a new instance of for deserialization. - protected TrackedResourceData() - { - } - - /// Resource tags. - public IDictionary Tags { get; } - /// The geo-location where the resource lives. - public AzureLocation Location { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/UserAssignedIdentity.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/UserAssignedIdentity.Serialization.cs deleted file mode 100644 index ad78fdb6bc..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/UserAssignedIdentity.Serialization.cs +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - [JsonConverter(typeof(UserAssignedIdentityConverter))] - public partial class UserAssignedIdentity : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(UserAssignedIdentity)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(PrincipalId)) - { - writer.WritePropertyName("principalId"u8); - writer.WriteStringValue(PrincipalId.Value); - } - if (options.Format != "W" && Optional.IsDefined(ClientId)) - { - writer.WritePropertyName("clientId"u8); - writer.WriteStringValue(ClientId.Value); - } - } - - UserAssignedIdentity IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(UserAssignedIdentity)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeUserAssignedIdentity(document.RootElement, options); - } - - internal static UserAssignedIdentity DeserializeUserAssignedIdentity(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - Guid? principalId = default; - Guid? clientId = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("principalId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - principalId = property.Value.GetGuid(); - continue; - } - if (property.NameEquals("clientId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - clientId = property.Value.GetGuid(); - continue; - } - } - return new UserAssignedIdentity(principalId, clientId); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PrincipalId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" principalId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PrincipalId)) - { - builder.Append(" principalId: "); - builder.AppendLine($"'{PrincipalId.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ClientId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" clientId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ClientId)) - { - builder.Append(" clientId: "); - builder.AppendLine($"'{ClientId.Value.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(UserAssignedIdentity)} does not support writing '{options.Format}' format."); - } - } - - UserAssignedIdentity IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeUserAssignedIdentity(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(UserAssignedIdentity)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class UserAssignedIdentityConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, UserAssignedIdentity model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model, ModelSerializationExtensions.WireOptions); - } - - public override UserAssignedIdentity Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeUserAssignedIdentity(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/UserAssignedIdentity.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/UserAssignedIdentity.cs deleted file mode 100644 index 727197fddd..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Common/Generated/Models/UserAssignedIdentity.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// User assigned identity properties. - [PropertyReferenceType] - public partial class UserAssignedIdentity - { - /// Initializes a new instance of . - [InitializationConstructor] - public UserAssignedIdentity() - { - } - - /// Initializes a new instance of . - /// The principal ID of the assigned identity. - /// The client ID of the assigned identity. - [SerializationConstructor] - internal UserAssignedIdentity(Guid? principalId, Guid? clientId) - { - PrincipalId = principalId; - ClientId = clientId; - } - - /// The principal ID of the assigned identity. - [WirePath("principalId")] - public Guid? PrincipalId { get; } - /// The client ID of the assigned identity. - [WirePath("clientId")] - public Guid? ClientId { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Directory.Build.props b/tests/dotnet-upgrade/dotnet-aot-compat/after/Directory.Build.props deleted file mode 100644 index 8c119d5413..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Directory.Build.props +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Directory.Packages.props b/tests/dotnet-upgrade/dotnet-aot-compat/after/Directory.Packages.props deleted file mode 100644 index 5fc7d2a08a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Directory.Packages.props +++ /dev/null @@ -1,10 +0,0 @@ - - - true - - - - - - - diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ExperimentalAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ExperimentalAttribute.cs deleted file mode 100644 index 9465ac0f52..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ExperimentalAttribute.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#if !NET8_0_OR_GREATER - -#nullable enable - -namespace System.Diagnostics.CodeAnalysis -{ - /// - /// Indicates that an API is experimental and it may change in the future. - /// - /// - /// This attribute allows call sites to be flagged with a diagnostic that indicates that an experimental - /// feature is used. Authors can use this attribute to ship preview features in their assemblies. - /// - [AttributeUsage(AttributeTargets.Assembly | - AttributeTargets.Module | - AttributeTargets.Class | - AttributeTargets.Struct | - AttributeTargets.Enum | - AttributeTargets.Constructor | - AttributeTargets.Method | - AttributeTargets.Property | - AttributeTargets.Field | - AttributeTargets.Event | - AttributeTargets.Interface | - AttributeTargets.Delegate, Inherited = false)] - internal sealed class ExperimentalAttribute : Attribute - { - /// - /// Initializes a new instance of the class, specifying the ID that the compiler will use - /// when reporting a use of the API the attribute applies to. - /// - /// The ID that the compiler will use when reporting a use of the API the attribute applies to. - public ExperimentalAttribute(string diagnosticId) - { - DiagnosticId = diagnosticId; - } - - /// - /// Gets the ID that the compiler will use when reporting a use of the API the attribute applies to. - /// - /// The unique diagnostic ID. - /// - /// The diagnostic ID is shown in build output for warnings and errors. - /// This property represents the unique ID that can be used to suppress the warnings or errors, if needed. - /// - public string DiagnosticId { get; } - - /// - /// Gets or sets the URL for corresponding documentation. - /// The API accepts a format string instead of an actual URL, creating a generic URL that includes the diagnostic ID. - /// - /// The format string that represents a URL to corresponding documentation. - /// An example format string is https://contoso.com/obsoletion-warnings/{0}. - public string? UrlFormat { get; set; } - } -} -#endif diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Extensions/ArmClientBuilderExtensions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Extensions/ArmClientBuilderExtensions.cs deleted file mode 100644 index 2a6acd69ed..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Extensions/ArmClientBuilderExtensions.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.Diagnostics.CodeAnalysis; -using Azure.Core.Extensions; -using Azure.ResourceManager; - -namespace Microsoft.Extensions.Azure -{ - /// - /// Extension methods to add client to clients builder. - /// - public static class ArmClientBuilderExtensions - { - /// - /// Registers an instance with the provided - /// - public static IAzureClientBuilder AddArmClient(this TBuilder builder, string defaultSubscription) - where TBuilder : IAzureClientFactoryBuilderWithCredential - { - return builder.RegisterClientFactory((options, cred) => new ArmClient(cred, defaultSubscription, options)); - } - - /// - /// Registers an instance with connection options loaded from the provided instance. - /// - [RequiresDynamicCode("Uses code generation for registration")] - [RequiresUnreferencedCode("Uses code generation for registration")] - public static IAzureClientBuilder AddArmClient(this TBuilder builder, TConfiguration configuration) - where TBuilder : IAzureClientFactoryBuilderWithConfiguration - { - return builder.RegisterClientFactory(configuration); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/GenericOperationSource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/GenericOperationSource.cs deleted file mode 100644 index 3c9c96b456..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/GenericOperationSource.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Diagnostics.CodeAnalysis; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; - -namespace Azure.ResourceManager -{ - internal class GenericOperationSource<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> : IOperationSource - { - private readonly ArmClient _client; - private readonly bool _isResource; - - public GenericOperationSource(ArmClient client, bool isResource) - { - _client = client; - _isResource = isResource; - } - - T IOperationSource.CreateResult(Response response, CancellationToken cancellationToken) - => CreateResult(response); - - ValueTask IOperationSource.CreateResultAsync(Response response, CancellationToken cancellationToken) - => new ValueTask(CreateResult(response)); - - private T CreateResult(Response response) - { - // This call will never be invoked with a collection of models, so we can safely disable the warning -#pragma warning disable AZC0150 // Use ModelReaderWriter overloads with ModelReaderWriterContext - object data = ModelReaderWriter.Read(response.Content, typeof(T)); -#pragma warning restore AZC0150 // Use ModelReaderWriter overloads with ModelReaderWriterContext - return _isResource - ? (T)Activator.CreateInstance(typeof(T), BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { _client, data }, null) - : (T)data; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Custom/HelperSuppressions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Custom/HelperSuppressions.cs deleted file mode 100644 index dfe77b4da6..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Custom/HelperSuppressions.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using Azure.Core; - -[assembly: CodeGenSuppressType("Azure.ResourceManager.Optional")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.ChangeTrackingList")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.RequestContentHelper")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.Argument")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.Utf8JsonRequestContent")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.ChangeTrackingDictionary")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.ModelSerializationExtensions")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.BicepSerializationHelpers")] diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Custom/ManagementGroupResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Custom/ManagementGroupResource.cs deleted file mode 100644 index 809c4fff69..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Custom/ManagementGroupResource.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ComponentModel; -using System.Threading; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups.Models; - -[assembly:CodeGenSuppressType("SearchOptions")] -[assembly:CodeGenSuppressType("EntityViewOptions")] -[assembly:CodeGenSuppressType("TenantExtensions")] // Moved code to Custom/Tenant -[assembly:CodeGenSuppressType("AzureAsyncOperationResults")] -[assembly:CodeGenSuppressType("ErrorResponse")] -[assembly:CodeGenSuppressType("ErrorDetails")] // No target and additionalInfo properties, therefore it's not replaced by common type -[assembly:CodeGenSuppressType("ManagementGroupUpdateOperation")] -namespace Azure.ResourceManager.ManagementGroups -{ - /// A Class representing a ManagementGroup along with the instance operations that can be performed on it. - public partial class ManagementGroupResource : ArmResource - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Custom/Models/ManagementGroupNameAvailabilityContent.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Custom/Models/ManagementGroupNameAvailabilityContent.cs deleted file mode 100644 index a033177eb0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Custom/Models/ManagementGroupNameAvailabilityContent.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupNameAvailabilityContent - { - /// Initializes a new instance of ManagementGroupNameAvailabilityContent. - public ManagementGroupNameAvailabilityContent() - { - ResourceType = "Microsoft.Management/managementGroups"; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Extensions/ArmClient.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Extensions/ArmClient.cs deleted file mode 100644 index 6881f263fc..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Extensions/ArmClient.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using Azure.Core; -using Azure.ResourceManager.ManagementGroups; - -namespace Azure.ResourceManager -{ - public partial class ArmClient - { - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual ManagementGroupResource GetManagementGroupResource(ResourceIdentifier id) - { - ManagementGroupResource.ValidateResourceId(id); - return new ManagementGroupResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual ManagementGroupSubscriptionResource GetManagementGroupSubscriptionResource(ResourceIdentifier id) - { - ManagementGroupSubscriptionResource.ValidateResourceId(id); - return new ManagementGroupSubscriptionResource(this, id); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Extensions/TenantResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Extensions/TenantResource.cs deleted file mode 100644 index 457e521a66..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Extensions/TenantResource.cs +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.ResourceManager.ManagementGroups; -using Azure.ResourceManager.ManagementGroups.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class TenantResource - { - /// Gets a collection of ManagementGroupResources in the TenantResource. - /// An object representing collection of ManagementGroupResources and their operations over a ManagementGroupResource. - public virtual ManagementGroupCollection GetManagementGroups() - { - return GetCachedClient(client => new ManagementGroupCollection(client, Id)); - } - - /// - /// Get the details of the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetManagementGroupAsync(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - return await GetManagementGroups().GetAsync(groupId, expand, recurse, filter, cacheControl, cancellationToken).ConfigureAwait(false); - } - - /// - /// Get the details of the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetManagementGroup(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - return GetManagementGroups().Get(groupId, expand, recurse, filter, cacheControl, cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Internal/WirePathAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Internal/WirePathAttribute.cs deleted file mode 100644 index 9f3fd65374..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Internal/WirePathAttribute.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.ManagementGroups -{ - [AttributeUsage(AttributeTargets.Property)] - internal class WirePathAttribute : Attribute - { - private string _wirePath; - - public WirePathAttribute(string wirePath) - { - _wirePath = wirePath; - } - - public override string ToString() - { - return _wirePath; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupOperationSource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupOperationSource.cs deleted file mode 100644 index b7ed659f6a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupOperationSource.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.ClientModel.Primitives; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups -{ - internal class ManagementGroupOperationSource : IOperationSource - { - private readonly ArmClient _client; - - internal ManagementGroupOperationSource(ArmClient client) - { - _client = client; - } - - ManagementGroupResource IOperationSource.CreateResult(Response response, CancellationToken cancellationToken) - { - var data = ModelReaderWriter.Read(response.Content, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default); - return new ManagementGroupResource(_client, data); - } - - async ValueTask IOperationSource.CreateResultAsync(Response response, CancellationToken cancellationToken) - { - var data = ModelReaderWriter.Read(response.Content, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default); - return await Task.FromResult(new ManagementGroupResource(_client, data)).ConfigureAwait(false); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperation.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperation.cs deleted file mode 100644 index ab650d6389..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperation.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.ManagementGroups -{ -#pragma warning disable SA1649 // File name should match first type name - internal class ManagementGroupsArmOperation : ArmOperation -#pragma warning restore SA1649 // File name should match first type name - { - private readonly OperationInternal _operation; - private readonly RehydrationToken? _completeRehydrationToken; - private readonly NextLinkOperationImplementation _nextLinkOperation; - private readonly string _operationId; - - /// Initializes a new instance of ManagementGroupsArmOperation for mocking. - protected ManagementGroupsArmOperation() - { - } - - internal ManagementGroupsArmOperation(Response response, RehydrationToken? rehydrationToken = null) - { - _operation = OperationInternal.Succeeded(response); - _completeRehydrationToken = rehydrationToken; - _operationId = GetOperationId(rehydrationToken); - } - - internal ManagementGroupsArmOperation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response, OperationFinalStateVia finalStateVia, bool skipApiVersionOverride = false, string apiVersionOverrideValue = null) - { - var nextLinkOperation = NextLinkOperationImplementation.Create(pipeline, request.Method, request.Uri.ToUri(), response, finalStateVia, skipApiVersionOverride, apiVersionOverrideValue); - if (nextLinkOperation is NextLinkOperationImplementation nextLinkOperationValue) - { - _nextLinkOperation = nextLinkOperationValue; - _operationId = _nextLinkOperation.OperationId; - } - else - { - _completeRehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(request.Method, request.Uri.ToUri(), response, finalStateVia); - _operationId = GetOperationId(_completeRehydrationToken); - } - _operation = new OperationInternal(nextLinkOperation, clientDiagnostics, response, "ManagementGroupsArmOperation", fallbackStrategy: new SequentialDelayStrategy()); - } - - private string GetOperationId(RehydrationToken? rehydrationToken) - { - if (rehydrationToken is null) - { - return null; - } - var lroDetails = ModelReaderWriter.Write(rehydrationToken, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default).ToObjectFromJson>(ResourceManagerJsonContext.Default.DictionaryStringString); - return lroDetails["id"]; - } - /// - public override string Id => _operationId ?? NextLinkOperationImplementation.NotSet; - - /// - public override RehydrationToken? GetRehydrationToken() => _nextLinkOperation?.GetRehydrationToken() ?? _completeRehydrationToken; - - /// - public override bool HasCompleted => _operation.HasCompleted; - - /// - public override Response GetRawResponse() => _operation.RawResponse; - - /// - public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); - - /// - public override ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); - - /// - public override Response WaitForCompletionResponse(CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponse(cancellationToken); - - /// - public override Response WaitForCompletionResponse(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponse(pollingInterval, cancellationToken); - - /// - public override ValueTask WaitForCompletionResponseAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponseAsync(cancellationToken); - - /// - public override ValueTask WaitForCompletionResponseAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponseAsync(pollingInterval, cancellationToken); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperationOfT.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperationOfT.cs deleted file mode 100644 index 9d8c8c1b70..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperationOfT.cs +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.ManagementGroups -{ -#pragma warning disable SA1649 // File name should match first type name - internal class ManagementGroupsArmOperation : ArmOperation -#pragma warning restore SA1649 // File name should match first type name - { - private readonly OperationInternal _operation; - private readonly RehydrationToken? _completeRehydrationToken; - private readonly NextLinkOperationImplementation _nextLinkOperation; - private readonly string _operationId; - - /// Initializes a new instance of ManagementGroupsArmOperation for mocking. - protected ManagementGroupsArmOperation() - { - } - - internal ManagementGroupsArmOperation(Response response, RehydrationToken? rehydrationToken = null) - { - _operation = OperationInternal.Succeeded(response.GetRawResponse(), response.Value); - _completeRehydrationToken = rehydrationToken; - _operationId = GetOperationId(rehydrationToken); - } - - internal ManagementGroupsArmOperation(IOperationSource source, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response, OperationFinalStateVia finalStateVia, bool skipApiVersionOverride = false, string apiVersionOverrideValue = null) - { - var nextLinkOperation = NextLinkOperationImplementation.Create(pipeline, request.Method, request.Uri.ToUri(), response, finalStateVia, skipApiVersionOverride, apiVersionOverrideValue); - if (nextLinkOperation is NextLinkOperationImplementation nextLinkOperationValue) - { - _nextLinkOperation = nextLinkOperationValue; - _operationId = _nextLinkOperation.OperationId; - } - else - { - _completeRehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(request.Method, request.Uri.ToUri(), response, finalStateVia); - _operationId = GetOperationId(_completeRehydrationToken); - } - _operation = new OperationInternal(NextLinkOperationImplementation.Create(source, nextLinkOperation), clientDiagnostics, response, "ManagementGroupsArmOperation", fallbackStrategy: new SequentialDelayStrategy()); - } - - private string GetOperationId(RehydrationToken? rehydrationToken) - { - if (rehydrationToken is null) - { - return null; - } - var lroDetails = ModelReaderWriter.Write(rehydrationToken, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default).ToObjectFromJson>(ResourceManagerJsonContext.Default.DictionaryStringString); - return lroDetails["id"]; - } - /// - public override string Id => _operationId ?? NextLinkOperationImplementation.NotSet; - - /// - public override RehydrationToken? GetRehydrationToken() => _nextLinkOperation?.GetRehydrationToken() ?? _completeRehydrationToken; - - /// - public override T Value => _operation.Value; - - /// - public override bool HasValue => _operation.HasValue; - - /// - public override bool HasCompleted => _operation.HasCompleted; - - /// - public override Response GetRawResponse() => _operation.RawResponse; - - /// - public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); - - /// - public override ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); - - /// - public override Response WaitForCompletion(CancellationToken cancellationToken = default) => _operation.WaitForCompletion(cancellationToken); - - /// - public override Response WaitForCompletion(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletion(pollingInterval, cancellationToken); - - /// - public override ValueTask> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken); - - /// - public override ValueTask> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupCollection.cs deleted file mode 100644 index 888276d7e4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupCollection.cs +++ /dev/null @@ -1,688 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups.Models; -using Azure.ResourceManager.Resources; - -namespace Azure.ResourceManager.ManagementGroups -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetManagementGroups method from an instance of . - /// - public partial class ManagementGroupCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _managementGroupClientDiagnostics; - private readonly ManagementGroupsRestOperations _managementGroupRestClient; - private readonly ClientDiagnostics _entitiesClientDiagnostics; - private readonly EntitiesRestOperations _entitiesRestClient; - - /// Initializes a new instance of the class for mocking. - protected ManagementGroupCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal ManagementGroupCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementGroupClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.ManagementGroups", ManagementGroupResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ManagementGroupResource.ResourceType, out string managementGroupApiVersion); - _managementGroupRestClient = new ManagementGroupsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementGroupApiVersion); - _entitiesClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.ManagementGroups", ProviderConstants.DefaultProviderNamespace, Diagnostics); - _entitiesRestClient = new EntitiesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != TenantResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, TenantResource.ResourceType), nameof(id)); - } - - /// - /// Create or update a management group. - /// If a management group is already created and a subsequent create request is issued with different properties, the management group properties will be updated. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Management Group ID. - /// Management group creation parameters. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string groupId, ManagementGroupCreateOrUpdateContent content, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNull(content, nameof(content)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _managementGroupRestClient.CreateOrUpdateAsync(groupId, content, cacheControl, cancellationToken).ConfigureAwait(false); - var operation = new ManagementGroupsArmOperation(new ManagementGroupOperationSource(Client), _managementGroupClientDiagnostics, Pipeline, _managementGroupRestClient.CreateCreateOrUpdateRequest(groupId, content, cacheControl).Request, response, OperationFinalStateVia.AzureAsyncOperation); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Create or update a management group. - /// If a management group is already created and a subsequent create request is issued with different properties, the management group properties will be updated. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Management Group ID. - /// Management group creation parameters. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string groupId, ManagementGroupCreateOrUpdateContent content, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNull(content, nameof(content)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = _managementGroupRestClient.CreateOrUpdate(groupId, content, cacheControl, cancellationToken); - var operation = new ManagementGroupsArmOperation(new ManagementGroupOperationSource(Client), _managementGroupClientDiagnostics, Pipeline, _managementGroupRestClient.CreateCreateOrUpdateRequest(groupId, content, cacheControl).Request, response, OperationFinalStateVia.AzureAsyncOperation); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Get the details of the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.Get"); - scope.Start(); - try - { - var response = await _managementGroupRestClient.GetAsync(groupId, expand, recurse, filter, cacheControl, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Get the details of the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.Get"); - scope.Start(); - try - { - var response = _managementGroupRestClient.Get(groupId, expand, recurse, filter, cacheControl, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// List management groups for the authenticated user. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups - /// - /// - /// Operation Id - /// ManagementGroups_List - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string cacheControl = null, string skipToken = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupRestClient.CreateListRequest(cacheControl, skipToken); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupRestClient.CreateListNextPageRequest(nextLink, cacheControl, skipToken); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new ManagementGroupResource(Client, ManagementGroupData.DeserializeManagementGroupData(e)), _managementGroupClientDiagnostics, Pipeline, "ManagementGroupCollection.GetAll", "value", "@nextLink", cancellationToken); - } - - /// - /// List management groups for the authenticated user. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups - /// - /// - /// Operation Id - /// ManagementGroups_List - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string cacheControl = null, string skipToken = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupRestClient.CreateListRequest(cacheControl, skipToken); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupRestClient.CreateListNextPageRequest(nextLink, cacheControl, skipToken); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new ManagementGroupResource(Client, ManagementGroupData.DeserializeManagementGroupData(e)), _managementGroupClientDiagnostics, Pipeline, "ManagementGroupCollection.GetAll", "value", "@nextLink", cancellationToken); - } - - /// - /// Checks if the specified management group name is valid and unique - /// - /// - /// Request Path - /// /providers/Microsoft.Management/checkNameAvailability - /// - /// - /// Operation Id - /// ManagementGroups_CheckNameAvailability - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management group name availability check parameters. - /// The cancellation token to use. - /// is null. - public virtual async Task> CheckNameAvailabilityAsync(ManagementGroupNameAvailabilityContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.CheckNameAvailability"); - scope.Start(); - try - { - var response = await _managementGroupRestClient.CheckNameAvailabilityAsync(content, cancellationToken).ConfigureAwait(false); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks if the specified management group name is valid and unique - /// - /// - /// Request Path - /// /providers/Microsoft.Management/checkNameAvailability - /// - /// - /// Operation Id - /// ManagementGroups_CheckNameAvailability - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management group name availability check parameters. - /// The cancellation token to use. - /// is null. - public virtual Response CheckNameAvailability(ManagementGroupNameAvailabilityContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.CheckNameAvailability"); - scope.Start(); - try - { - var response = _managementGroupRestClient.CheckNameAvailability(content, cancellationToken); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// List all entities (Management Groups, Subscriptions, etc.) for the authenticated user. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/getEntities - /// - /// - /// Operation Id - /// Entities_List - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// - /// A property bag which contains all the parameters of this method except the LRO qualifier and request context parameter. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetEntitiesAsync(ManagementGroupCollectionGetEntitiesOptions options, CancellationToken cancellationToken = default) - { - options ??= new ManagementGroupCollectionGetEntitiesOptions(); - - HttpMessage FirstPageRequest(int? pageSizeHint) => _entitiesRestClient.CreateListRequest(options.SkipToken, options.Skip, options.Top, options.Select, options.Search, options.Filter, options.View, options.GroupName, options.CacheControl); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _entitiesRestClient.CreateListNextPageRequest(nextLink, options.SkipToken, options.Skip, options.Top, options.Select, options.Search, options.Filter, options.View, options.GroupName, options.CacheControl); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => EntityData.DeserializeEntityData(e), _entitiesClientDiagnostics, Pipeline, "ManagementGroupCollection.GetEntities", "value", "nextLink", cancellationToken); - } - - /// - /// List all entities (Management Groups, Subscriptions, etc.) for the authenticated user. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/getEntities - /// - /// - /// Operation Id - /// Entities_List - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// - /// A property bag which contains all the parameters of this method except the LRO qualifier and request context parameter. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetEntities(ManagementGroupCollectionGetEntitiesOptions options, CancellationToken cancellationToken = default) - { - options ??= new ManagementGroupCollectionGetEntitiesOptions(); - - HttpMessage FirstPageRequest(int? pageSizeHint) => _entitiesRestClient.CreateListRequest(options.SkipToken, options.Skip, options.Top, options.Select, options.Search, options.Filter, options.View, options.GroupName, options.CacheControl); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _entitiesRestClient.CreateListNextPageRequest(nextLink, options.SkipToken, options.Skip, options.Top, options.Select, options.Search, options.Filter, options.View, options.GroupName, options.CacheControl); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => EntityData.DeserializeEntityData(e), _entitiesClientDiagnostics, Pipeline, "ManagementGroupCollection.GetEntities", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.Exists"); - scope.Start(); - try - { - var response = await _managementGroupRestClient.GetAsync(groupId, expand, recurse, filter, cacheControl, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.Exists"); - scope.Start(); - try - { - var response = _managementGroupRestClient.Get(groupId, expand, recurse, filter, cacheControl, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _managementGroupRestClient.GetAsync(groupId, expand, recurse, filter, cacheControl, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.GetIfExists"); - scope.Start(); - try - { - var response = _managementGroupRestClient.Get(groupId, expand, recurse, filter, cacheControl, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupData.Serialization.cs deleted file mode 100644 index 95fa34862f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupData.Serialization.cs +++ /dev/null @@ -1,383 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.ManagementGroups.Models; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.ManagementGroups -{ - public partial class ManagementGroupData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (Optional.IsDefined(TenantId)) - { - writer.WritePropertyName("tenantId"u8); - writer.WriteStringValue(TenantId.Value); - } - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (Optional.IsDefined(Details)) - { - writer.WritePropertyName("details"u8); - writer.WriteObjectValue(Details, options); - } - if (Optional.IsCollectionDefined(Children)) - { - if (Children != null) - { - writer.WritePropertyName("children"u8); - writer.WriteStartArray(); - foreach (var item in Children) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - else - { - writer.WriteNull("children"); - } - } - writer.WriteEndObject(); - } - - ManagementGroupData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupData(document.RootElement, options); - } - - internal static ManagementGroupData DeserializeManagementGroupData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - Guid? tenantId = default; - string displayName = default; - ManagementGroupInfo details = default; - IReadOnlyList children = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.SystemData); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("tenantId"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - tenantId = property0.Value.GetGuid(); - continue; - } - if (property0.NameEquals("displayName"u8)) - { - displayName = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("details"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - details = ManagementGroupInfo.DeserializeManagementGroupInfo(property0.Value, options); - continue; - } - if (property0.NameEquals("children"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - children = null; - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(ManagementGroupChildInfo.DeserializeManagementGroupChildInfo(item, options)); - } - children = array; - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupData( - id, - name, - type, - systemData, - tenantId, - displayName, - details, - children ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.Append(" properties:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TenantId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenantId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TenantId)) - { - builder.Append(" tenantId: "); - builder.AppendLine($"'{TenantId.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Details), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" details: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Details)) - { - builder.Append(" details: "); - BicepSerializationHelpers.AppendChildObject(builder, Details, options, 4, false, " details: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Children), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" children: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Children)) - { - if (Children.Any()) - { - builder.Append(" children: "); - builder.AppendLine("["); - foreach (var item in Children) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 6, true, " children: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine(" }"); - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementGroupData)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupData.cs deleted file mode 100644 index 5b5b364b1d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupData.cs +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.ManagementGroups.Models; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.ManagementGroups -{ - /// - /// A class representing the ManagementGroup data model. - /// The management group details. - /// - public partial class ManagementGroupData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagementGroupData() - { - Children = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000. - /// The friendly name of the management group. - /// The details of a management group. - /// The list of children. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, Guid? tenantId, string displayName, ManagementGroupInfo details, IReadOnlyList children, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - TenantId = tenantId; - DisplayName = displayName; - Details = details; - Children = children; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000. - [WirePath("properties.tenantId")] - public Guid? TenantId { get; } - /// The friendly name of the management group. - [WirePath("properties.displayName")] - public string DisplayName { get; } - /// The details of a management group. - [WirePath("properties.details")] - public ManagementGroupInfo Details { get; } - /// The list of children. - [WirePath("properties.children")] - public IReadOnlyList Children { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupResource.Serialization.cs deleted file mode 100644 index daf7ad8478..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.ManagementGroups -{ - public partial class ManagementGroupResource : IJsonModel - { - private static ManagementGroupData s_dataDeserializationInstance; - private static ManagementGroupData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - ManagementGroupData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - ManagementGroupData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupResource.cs deleted file mode 100644 index 596e9a0bbf..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupResource.cs +++ /dev/null @@ -1,505 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups.Models; -using Azure.ResourceManager.Resources; - -namespace Azure.ResourceManager.ManagementGroups -{ - /// - /// A Class representing a ManagementGroup along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetManagementGroupResource method. - /// Otherwise you can get one from its parent resource using the GetManagementGroup method. - /// - public partial class ManagementGroupResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The groupId. - public static ResourceIdentifier CreateResourceIdentifier(string groupId) - { - var resourceId = $"/providers/Microsoft.Management/managementGroups/{groupId}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _managementGroupClientDiagnostics; - private readonly ManagementGroupsRestOperations _managementGroupRestClient; - private readonly ManagementGroupData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Management/managementGroups"; - - /// Initializes a new instance of the class for mocking. - protected ManagementGroupResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal ManagementGroupResource(ArmClient client, ManagementGroupData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal ManagementGroupResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementGroupClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.ManagementGroups", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string managementGroupApiVersion); - _managementGroupRestClient = new ManagementGroupsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementGroupApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual ManagementGroupData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// Gets a collection of ManagementGroupSubscriptionResources in the ManagementGroup. - /// An object representing collection of ManagementGroupSubscriptionResources and their operations over a ManagementGroupSubscriptionResource. - public virtual ManagementGroupSubscriptionCollection GetManagementGroupSubscriptions() - { - return GetCachedClient(client => new ManagementGroupSubscriptionCollection(client, Id)); - } - - /// - /// Retrieves details about given subscription which is associated with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetManagementGroupSubscriptionAsync(string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - return await GetManagementGroupSubscriptions().GetAsync(subscriptionId, cacheControl, cancellationToken).ConfigureAwait(false); - } - - /// - /// Retrieves details about given subscription which is associated with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetManagementGroupSubscription(string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - return GetManagementGroupSubscriptions().Get(subscriptionId, cacheControl, cancellationToken); - } - - /// - /// Get the details of the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual async Task> GetAsync(ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupResource.Get"); - scope.Start(); - try - { - var response = await _managementGroupRestClient.GetAsync(Id.Name, expand, recurse, filter, cacheControl, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Get the details of the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual Response Get(ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupResource.Get"); - scope.Start(); - try - { - var response = _managementGroupRestClient.Get(Id.Name, expand, recurse, filter, cacheControl, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Delete management group. - /// If a management group contains child resources, the request will fail. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Delete - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual async Task DeleteAsync(WaitUntil waitUntil, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupResource.Delete"); - scope.Start(); - try - { - var response = await _managementGroupRestClient.DeleteAsync(Id.Name, cacheControl, cancellationToken).ConfigureAwait(false); - var operation = new ManagementGroupsArmOperation(_managementGroupClientDiagnostics, Pipeline, _managementGroupRestClient.CreateDeleteRequest(Id.Name, cacheControl).Request, response, OperationFinalStateVia.AzureAsyncOperation); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Delete management group. - /// If a management group contains child resources, the request will fail. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Delete - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupResource.Delete"); - scope.Start(); - try - { - var response = _managementGroupRestClient.Delete(Id.Name, cacheControl, cancellationToken); - var operation = new ManagementGroupsArmOperation(_managementGroupClientDiagnostics, Pipeline, _managementGroupRestClient.CreateDeleteRequest(Id.Name, cacheControl).Request, response, OperationFinalStateVia.AzureAsyncOperation); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Update a management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Update - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management group patch parameters. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(ManagementGroupPatch patch, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(patch, nameof(patch)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupResource.Update"); - scope.Start(); - try - { - var response = await _managementGroupRestClient.UpdateAsync(Id.Name, patch, cacheControl, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new ManagementGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Update a management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Update - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management group patch parameters. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - public virtual Response Update(ManagementGroupPatch patch, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(patch, nameof(patch)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupResource.Update"); - scope.Start(); - try - { - var response = _managementGroupRestClient.Update(Id.Name, patch, cacheControl, cancellationToken); - return Response.FromValue(new ManagementGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// List all entities that descend from a management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/descendants - /// - /// - /// Operation Id - /// ManagementGroups_GetDescendants - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetDescendantsAsync(string skipToken = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupRestClient.CreateGetDescendantsRequest(Id.Name, skipToken, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupRestClient.CreateGetDescendantsNextPageRequest(nextLink, Id.Name, skipToken, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => DescendantData.DeserializeDescendantData(e), _managementGroupClientDiagnostics, Pipeline, "ManagementGroupResource.GetDescendants", "value", "nextLink", cancellationToken); - } - - /// - /// List all entities that descend from a management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/descendants - /// - /// - /// Operation Id - /// ManagementGroups_GetDescendants - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetDescendants(string skipToken = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupRestClient.CreateGetDescendantsRequest(Id.Name, skipToken, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupRestClient.CreateGetDescendantsNextPageRequest(nextLink, Id.Name, skipToken, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => DescendantData.DeserializeDescendantData(e), _managementGroupClientDiagnostics, Pipeline, "ManagementGroupResource.GetDescendants", "value", "nextLink", cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionCollection.cs deleted file mode 100644 index 9f8a56d321..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionCollection.cs +++ /dev/null @@ -1,516 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.ManagementGroups -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetManagementGroupSubscriptions method from an instance of . - /// - public partial class ManagementGroupSubscriptionCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _managementGroupSubscriptionClientDiagnostics; - private readonly ManagementGroupSubscriptionsRestOperations _managementGroupSubscriptionRestClient; - - /// Initializes a new instance of the class for mocking. - protected ManagementGroupSubscriptionCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal ManagementGroupSubscriptionCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementGroupSubscriptionClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.ManagementGroups", ManagementGroupSubscriptionResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ManagementGroupSubscriptionResource.ResourceType, out string managementGroupSubscriptionApiVersion); - _managementGroupSubscriptionRestClient = new ManagementGroupSubscriptionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementGroupSubscriptionApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ManagementGroupResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ManagementGroupResource.ResourceType), nameof(id)); - } - - /// - /// Associates existing subscription with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_Create - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _managementGroupSubscriptionRestClient.CreateAsync(Id.Name, subscriptionId, cacheControl, cancellationToken).ConfigureAwait(false); - var uri = _managementGroupSubscriptionRestClient.CreateCreateRequestUri(Id.Name, subscriptionId, cacheControl); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ManagementGroupsArmOperation(Response.FromValue(new ManagementGroupSubscriptionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Associates existing subscription with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_Create - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = _managementGroupSubscriptionRestClient.Create(Id.Name, subscriptionId, cacheControl, cancellationToken); - var uri = _managementGroupSubscriptionRestClient.CreateCreateRequestUri(Id.Name, subscriptionId, cacheControl); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ManagementGroupsArmOperation(Response.FromValue(new ManagementGroupSubscriptionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Retrieves details about given subscription which is associated with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionCollection.Get"); - scope.Start(); - try - { - var response = await _managementGroupSubscriptionRestClient.GetSubscriptionAsync(Id.Name, subscriptionId, cacheControl, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupSubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Retrieves details about given subscription which is associated with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionCollection.Get"); - scope.Start(); - try - { - var response = _managementGroupSubscriptionRestClient.GetSubscription(Id.Name, subscriptionId, cacheControl, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupSubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Retrieves details about all subscriptions which are associated with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscriptionsUnderManagementGroup - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string skipToken = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupSubscriptionRestClient.CreateGetSubscriptionsUnderManagementGroupRequest(Id.Name, skipToken); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupSubscriptionRestClient.CreateGetSubscriptionsUnderManagementGroupNextPageRequest(nextLink, Id.Name, skipToken); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new ManagementGroupSubscriptionResource(Client, ManagementGroupSubscriptionData.DeserializeManagementGroupSubscriptionData(e)), _managementGroupSubscriptionClientDiagnostics, Pipeline, "ManagementGroupSubscriptionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Retrieves details about all subscriptions which are associated with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscriptionsUnderManagementGroup - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string skipToken = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupSubscriptionRestClient.CreateGetSubscriptionsUnderManagementGroupRequest(Id.Name, skipToken); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupSubscriptionRestClient.CreateGetSubscriptionsUnderManagementGroupNextPageRequest(nextLink, Id.Name, skipToken); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new ManagementGroupSubscriptionResource(Client, ManagementGroupSubscriptionData.DeserializeManagementGroupSubscriptionData(e)), _managementGroupSubscriptionClientDiagnostics, Pipeline, "ManagementGroupSubscriptionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionCollection.Exists"); - scope.Start(); - try - { - var response = await _managementGroupSubscriptionRestClient.GetSubscriptionAsync(Id.Name, subscriptionId, cacheControl, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionCollection.Exists"); - scope.Start(); - try - { - var response = _managementGroupSubscriptionRestClient.GetSubscription(Id.Name, subscriptionId, cacheControl, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _managementGroupSubscriptionRestClient.GetSubscriptionAsync(Id.Name, subscriptionId, cacheControl, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupSubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionCollection.GetIfExists"); - scope.Start(); - try - { - var response = _managementGroupSubscriptionRestClient.GetSubscription(Id.Name, subscriptionId, cacheControl, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupSubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionData.Serialization.cs deleted file mode 100644 index 40d5766cda..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionData.Serialization.cs +++ /dev/null @@ -1,377 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.ManagementGroups.Models; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.ManagementGroups -{ - public partial class ManagementGroupSubscriptionData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupSubscriptionData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (Optional.IsDefined(Tenant)) - { - writer.WritePropertyName("tenant"u8); - writer.WriteStringValue(Tenant); - } - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (Optional.IsDefined(Parent)) - { - if (Parent != null) - { - writer.WritePropertyName("parent"u8); - writer.WriteObjectValue(Parent, options); - } - else - { - writer.WriteNull("parent"); - } - } - if (Optional.IsDefined(State)) - { - writer.WritePropertyName("state"u8); - writer.WriteStringValue(State); - } - writer.WriteEndObject(); - } - - ManagementGroupSubscriptionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupSubscriptionData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupSubscriptionData(document.RootElement, options); - } - - internal static ManagementGroupSubscriptionData DeserializeManagementGroupSubscriptionData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - string tenant = default; - string displayName = default; - DescendantParentGroupInfo parent = default; - string state = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.SystemData); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("tenant"u8)) - { - tenant = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("displayName"u8)) - { - displayName = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("parent"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - parent = null; - continue; - } - parent = DescendantParentGroupInfo.DeserializeDescendantParentGroupInfo(property0.Value, options); - continue; - } - if (property0.NameEquals("state"u8)) - { - state = property0.Value.GetString(); - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupSubscriptionData( - id, - name, - type, - systemData, - tenant, - displayName, - parent, - state, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.Append(" properties:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Tenant), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenant: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Tenant)) - { - builder.Append(" tenant: "); - if (Tenant.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Tenant}'''"); - } - else - { - builder.AppendLine($"'{Tenant}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue("ParentId", out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parent: "); - builder.AppendLine("{"); - builder.AppendLine(" parent: {"); - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - builder.AppendLine(" }"); - builder.AppendLine(" }"); - } - else - { - if (Optional.IsDefined(Parent)) - { - builder.Append(" parent: "); - BicepSerializationHelpers.AppendChildObject(builder, Parent, options, 4, false, " parent: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(State), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" state: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(State)) - { - builder.Append(" state: "); - if (State.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{State}'''"); - } - else - { - builder.AppendLine($"'{State}'"); - } - } - } - - builder.AppendLine(" }"); - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementGroupSubscriptionData)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupSubscriptionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupSubscriptionData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupSubscriptionData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionData.cs deleted file mode 100644 index 012a80ff0c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionData.cs +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.ManagementGroups.Models; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.ManagementGroups -{ - /// - /// A class representing the ManagementGroupSubscription data model. - /// The details of subscription under management group. - /// - public partial class ManagementGroupSubscriptionData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagementGroupSubscriptionData() - { - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The AAD Tenant ID associated with the subscription. For example, 00000000-0000-0000-0000-000000000000. - /// The friendly name of the subscription. - /// The ID of the parent management group. - /// The state of the subscription. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupSubscriptionData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, string tenant, string displayName, DescendantParentGroupInfo parent, string state, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - Tenant = tenant; - DisplayName = displayName; - Parent = parent; - State = state; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The AAD Tenant ID associated with the subscription. For example, 00000000-0000-0000-0000-000000000000. - [WirePath("properties.tenant")] - public string Tenant { get; } - /// The friendly name of the subscription. - [WirePath("properties.displayName")] - public string DisplayName { get; } - /// The ID of the parent management group. - internal DescendantParentGroupInfo Parent { get; } - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - [WirePath("properties.parent.id")] - public ResourceIdentifier ParentId - { - get => Parent?.Id; - } - - /// The state of the subscription. - [WirePath("properties.state")] - public string State { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionResource.Serialization.cs deleted file mode 100644 index 27395325f3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.ManagementGroups -{ - public partial class ManagementGroupSubscriptionResource : IJsonModel - { - private static ManagementGroupSubscriptionData s_dataDeserializationInstance; - private static ManagementGroupSubscriptionData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - ManagementGroupSubscriptionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - ManagementGroupSubscriptionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionResource.cs deleted file mode 100644 index 084663c338..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionResource.cs +++ /dev/null @@ -1,357 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.ManagementGroups -{ - /// - /// A Class representing a ManagementGroupSubscription along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetManagementGroupSubscriptionResource method. - /// Otherwise you can get one from its parent resource using the GetManagementGroupSubscription method. - /// - public partial class ManagementGroupSubscriptionResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The groupId. - /// The subscriptionId. - public static ResourceIdentifier CreateResourceIdentifier(string groupId, string subscriptionId) - { - var resourceId = $"/providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _managementGroupSubscriptionClientDiagnostics; - private readonly ManagementGroupSubscriptionsRestOperations _managementGroupSubscriptionRestClient; - private readonly ManagementGroupSubscriptionData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Management/managementGroups/subscriptions"; - - /// Initializes a new instance of the class for mocking. - protected ManagementGroupSubscriptionResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal ManagementGroupSubscriptionResource(ArmClient client, ManagementGroupSubscriptionData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal ManagementGroupSubscriptionResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementGroupSubscriptionClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.ManagementGroups", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string managementGroupSubscriptionApiVersion); - _managementGroupSubscriptionRestClient = new ManagementGroupSubscriptionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementGroupSubscriptionApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual ManagementGroupSubscriptionData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// Retrieves details about given subscription which is associated with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual async Task> GetAsync(string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionResource.Get"); - scope.Start(); - try - { - var response = await _managementGroupSubscriptionRestClient.GetSubscriptionAsync(Id.Parent.Name, Id.Name, cacheControl, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupSubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Retrieves details about given subscription which is associated with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual Response Get(string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionResource.Get"); - scope.Start(); - try - { - var response = _managementGroupSubscriptionRestClient.GetSubscription(Id.Parent.Name, Id.Name, cacheControl, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupSubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// De-associates subscription from the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_Delete - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual async Task DeleteAsync(WaitUntil waitUntil, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionResource.Delete"); - scope.Start(); - try - { - var response = await _managementGroupSubscriptionRestClient.DeleteAsync(Id.Parent.Name, Id.Name, cacheControl, cancellationToken).ConfigureAwait(false); - var uri = _managementGroupSubscriptionRestClient.CreateDeleteRequestUri(Id.Parent.Name, Id.Name, cacheControl); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ManagementGroupsArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// De-associates subscription from the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_Delete - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionResource.Delete"); - scope.Start(); - try - { - var response = _managementGroupSubscriptionRestClient.Delete(Id.Parent.Name, Id.Name, cacheControl, cancellationToken); - var uri = _managementGroupSubscriptionRestClient.CreateDeleteRequestUri(Id.Parent.Name, Id.Name, cacheControl); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ManagementGroupsArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Associates existing subscription with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_Create - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual async Task> UpdateAsync(WaitUntil waitUntil, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionResource.Update"); - scope.Start(); - try - { - var response = await _managementGroupSubscriptionRestClient.CreateAsync(Id.Parent.Name, Id.Name, cacheControl, cancellationToken).ConfigureAwait(false); - var uri = _managementGroupSubscriptionRestClient.CreateCreateRequestUri(Id.Parent.Name, Id.Name, cacheControl); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ManagementGroupsArmOperation(Response.FromValue(new ManagementGroupSubscriptionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Associates existing subscription with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_Create - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual ArmOperation Update(WaitUntil waitUntil, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionResource.Update"); - scope.Start(); - try - { - var response = _managementGroupSubscriptionRestClient.Create(Id.Parent.Name, Id.Name, cacheControl, cancellationToken); - var uri = _managementGroupSubscriptionRestClient.CreateCreateRequestUri(Id.Parent.Name, Id.Name, cacheControl); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ManagementGroupsArmOperation(Response.FromValue(new ManagementGroupSubscriptionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/CreateManagementGroupDetails.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/CreateManagementGroupDetails.Serialization.cs deleted file mode 100644 index ef52bc8121..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/CreateManagementGroupDetails.Serialization.cs +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class CreateManagementGroupDetails : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(CreateManagementGroupDetails)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Version)) - { - writer.WritePropertyName("version"u8); - writer.WriteNumberValue(Version.Value); - } - if (options.Format != "W" && Optional.IsDefined(UpdatedOn)) - { - writer.WritePropertyName("updatedTime"u8); - writer.WriteStringValue(UpdatedOn.Value, "O"); - } - if (options.Format != "W" && Optional.IsDefined(UpdatedBy)) - { - writer.WritePropertyName("updatedBy"u8); - writer.WriteStringValue(UpdatedBy); - } - if (Optional.IsDefined(Parent)) - { - writer.WritePropertyName("parent"u8); - writer.WriteObjectValue(Parent, options); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - CreateManagementGroupDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(CreateManagementGroupDetails)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeCreateManagementGroupDetails(document.RootElement, options); - } - - internal static CreateManagementGroupDetails DeserializeCreateManagementGroupDetails(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - int? version = default; - DateTimeOffset? updatedTime = default; - string updatedBy = default; - ManagementGroupParentCreateOptions parent = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("version"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - version = property.Value.GetInt32(); - continue; - } - if (property.NameEquals("updatedTime"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - updatedTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("updatedBy"u8)) - { - updatedBy = property.Value.GetString(); - continue; - } - if (property.NameEquals("parent"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - parent = ManagementGroupParentCreateOptions.DeserializeManagementGroupParentCreateOptions(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new CreateManagementGroupDetails(version, updatedTime, updatedBy, parent, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(CreateManagementGroupDetails)} does not support writing '{options.Format}' format."); - } - } - - CreateManagementGroupDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeCreateManagementGroupDetails(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(CreateManagementGroupDetails)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/CreateManagementGroupDetails.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/CreateManagementGroupDetails.cs deleted file mode 100644 index 6cfb0e466c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/CreateManagementGroupDetails.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The details of a management group used during creation. - public partial class CreateManagementGroupDetails - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public CreateManagementGroupDetails() - { - } - - /// Initializes a new instance of . - /// The version number of the object. - /// The date and time when this object was last updated. - /// The identity of the principal or process that updated the object. - /// (Optional) The ID of the parent management group used during creation. - /// Keeps track of any properties unknown to the library. - internal CreateManagementGroupDetails(int? version, DateTimeOffset? updatedOn, string updatedBy, ManagementGroupParentCreateOptions parent, IDictionary serializedAdditionalRawData) - { - Version = version; - UpdatedOn = updatedOn; - UpdatedBy = updatedBy; - Parent = parent; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The version number of the object. - [WirePath("version")] - public int? Version { get; } - /// The date and time when this object was last updated. - [WirePath("updatedTime")] - public DateTimeOffset? UpdatedOn { get; } - /// The identity of the principal or process that updated the object. - [WirePath("updatedBy")] - public string UpdatedBy { get; } - /// (Optional) The ID of the parent management group used during creation. - [WirePath("parent")] - public ManagementGroupParentCreateOptions Parent { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantData.Serialization.cs deleted file mode 100644 index b0a653ed4f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantData.Serialization.cs +++ /dev/null @@ -1,318 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class DescendantData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DescendantData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (Optional.IsDefined(DisplayName)) - { - if (DisplayName != null) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - else - { - writer.WriteNull("displayName"); - } - } - if (Optional.IsDefined(Parent)) - { - if (Parent != null) - { - writer.WritePropertyName("parent"u8); - writer.WriteObjectValue(Parent, options); - } - else - { - writer.WriteNull("parent"); - } - } - writer.WriteEndObject(); - } - - DescendantData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DescendantData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDescendantData(document.RootElement, options); - } - - internal static DescendantData DeserializeDescendantData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - string displayName = default; - DescendantParentGroupInfo parent = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.SystemData); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("displayName"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - displayName = null; - continue; - } - displayName = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("parent"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - parent = null; - continue; - } - parent = DescendantParentGroupInfo.DeserializeDescendantParentGroupInfo(property0.Value, options); - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new DescendantData( - id, - name, - type, - systemData, - displayName, - parent, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.Append(" properties:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue("ParentId", out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parent: "); - builder.AppendLine("{"); - builder.AppendLine(" parent: {"); - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - builder.AppendLine(" }"); - builder.AppendLine(" }"); - } - else - { - if (Optional.IsDefined(Parent)) - { - builder.Append(" parent: "); - BicepSerializationHelpers.AppendChildObject(builder, Parent, options, 4, false, " parent: "); - } - } - - builder.AppendLine(" }"); - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(DescendantData)} does not support writing '{options.Format}' format."); - } - } - - DescendantData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeDescendantData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DescendantData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantData.cs deleted file mode 100644 index b6d4f43ca7..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantData.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The descendant. - public partial class DescendantData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal DescendantData() - { - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The friendly name of the management group. - /// The ID of the parent management group. - /// Keeps track of any properties unknown to the library. - internal DescendantData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, string displayName, DescendantParentGroupInfo parent, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - DisplayName = displayName; - Parent = parent; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The friendly name of the management group. - [WirePath("properties.displayName")] - public string DisplayName { get; } - /// The ID of the parent management group. - internal DescendantParentGroupInfo Parent { get; } - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - [WirePath("properties.parent.id")] - public ResourceIdentifier ParentId - { - get => Parent?.Id; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantListResult.Serialization.cs deleted file mode 100644 index debf6320d5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - internal partial class DescendantListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DescendantListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - DescendantListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DescendantListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDescendantListResult(document.RootElement, options); - } - - internal static DescendantListResult DeserializeDescendantListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(DescendantData.DeserializeDescendantData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new DescendantListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(DescendantListResult)} does not support writing '{options.Format}' format."); - } - } - - DescendantListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeDescendantListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DescendantListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantListResult.cs deleted file mode 100644 index df6d43351c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// Describes the result of the request to view descendants. - internal partial class DescendantListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal DescendantListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The list of descendants. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal DescendantListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The list of descendants. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantParentGroupInfo.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantParentGroupInfo.Serialization.cs deleted file mode 100644 index 8d94b77a62..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantParentGroupInfo.Serialization.cs +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - internal partial class DescendantParentGroupInfo : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DescendantParentGroupInfo)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - DescendantParentGroupInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DescendantParentGroupInfo)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDescendantParentGroupInfo(document.RootElement, options); - } - - internal static DescendantParentGroupInfo DeserializeDescendantParentGroupInfo(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new DescendantParentGroupInfo(id, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(DescendantParentGroupInfo)} does not support writing '{options.Format}' format."); - } - } - - DescendantParentGroupInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeDescendantParentGroupInfo(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DescendantParentGroupInfo)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantParentGroupInfo.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantParentGroupInfo.cs deleted file mode 100644 index 5dd49bf750..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantParentGroupInfo.cs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The ID of the parent management group. - internal partial class DescendantParentGroupInfo - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal DescendantParentGroupInfo() - { - } - - /// Initializes a new instance of . - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// Keeps track of any properties unknown to the library. - internal DescendantParentGroupInfo(ResourceIdentifier id, IDictionary serializedAdditionalRawData) - { - Id = id; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - [WirePath("id")] - public ResourceIdentifier Id { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityData.Serialization.cs deleted file mode 100644 index 13036e65da..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityData.Serialization.cs +++ /dev/null @@ -1,686 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class EntityData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(EntityData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (Optional.IsDefined(TenantId)) - { - if (TenantId != null) - { - writer.WritePropertyName("tenantId"u8); - writer.WriteStringValue(TenantId.Value); - } - else - { - writer.WriteNull("tenantId"); - } - } - if (Optional.IsDefined(DisplayName)) - { - if (DisplayName != null) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - else - { - writer.WriteNull("displayName"); - } - } - if (Optional.IsDefined(Parent)) - { - writer.WritePropertyName("parent"u8); - JsonSerializer.Serialize(writer, Parent, ResourceManagerJsonContext.Default.SubResource); - } - if (Optional.IsDefined(Permissions)) - { - if (Permissions != null) - { - writer.WritePropertyName("permissions"u8); - writer.WriteStringValue(Permissions.Value.ToSerialString()); - } - else - { - writer.WriteNull("permissions"); - } - } - if (Optional.IsDefined(InheritedPermissions)) - { - if (InheritedPermissions != null) - { - writer.WritePropertyName("inheritedPermissions"u8); - writer.WriteStringValue(InheritedPermissions.Value.ToSerialString()); - } - else - { - writer.WriteNull("inheritedPermissions"); - } - } - if (Optional.IsDefined(NumberOfDescendants)) - { - if (NumberOfDescendants != null) - { - writer.WritePropertyName("numberOfDescendants"u8); - writer.WriteNumberValue(NumberOfDescendants.Value); - } - else - { - writer.WriteNull("numberOfDescendants"); - } - } - if (Optional.IsDefined(NumberOfChildren)) - { - if (NumberOfChildren != null) - { - writer.WritePropertyName("numberOfChildren"u8); - writer.WriteNumberValue(NumberOfChildren.Value); - } - else - { - writer.WriteNull("numberOfChildren"); - } - } - if (Optional.IsDefined(NumberOfChildGroups)) - { - if (NumberOfChildGroups != null) - { - writer.WritePropertyName("numberOfChildGroups"u8); - writer.WriteNumberValue(NumberOfChildGroups.Value); - } - else - { - writer.WriteNull("numberOfChildGroups"); - } - } - if (Optional.IsCollectionDefined(ParentDisplayNameChain)) - { - if (ParentDisplayNameChain != null) - { - writer.WritePropertyName("parentDisplayNameChain"u8); - writer.WriteStartArray(); - foreach (var item in ParentDisplayNameChain) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - else - { - writer.WriteNull("parentDisplayNameChain"); - } - } - if (Optional.IsCollectionDefined(ParentNameChain)) - { - if (ParentNameChain != null) - { - writer.WritePropertyName("parentNameChain"u8); - writer.WriteStartArray(); - foreach (var item in ParentNameChain) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - else - { - writer.WriteNull("parentNameChain"); - } - } - writer.WriteEndObject(); - } - - EntityData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(EntityData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeEntityData(document.RootElement, options); - } - - internal static EntityData DeserializeEntityData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - Guid? tenantId = default; - string displayName = default; - SubResource parent = default; - EntityPermission? permissions = default; - EntityPermission? inheritedPermissions = default; - int? numberOfDescendants = default; - int? numberOfChildren = default; - int? numberOfChildGroups = default; - IReadOnlyList parentDisplayNameChain = default; - IReadOnlyList parentNameChain = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.SystemData); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("tenantId"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - tenantId = null; - continue; - } - tenantId = property0.Value.GetGuid(); - continue; - } - if (property0.NameEquals("displayName"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - displayName = null; - continue; - } - displayName = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("parent"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - parent = JsonSerializer.Deserialize(property0.Value.GetRawText(), ResourceManagerJsonContext.Default.SubResource); - continue; - } - if (property0.NameEquals("permissions"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - permissions = null; - continue; - } - permissions = property0.Value.GetString().ToEntityPermission(); - continue; - } - if (property0.NameEquals("inheritedPermissions"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - inheritedPermissions = null; - continue; - } - inheritedPermissions = property0.Value.GetString().ToEntityPermission(); - continue; - } - if (property0.NameEquals("numberOfDescendants"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - numberOfDescendants = null; - continue; - } - numberOfDescendants = property0.Value.GetInt32(); - continue; - } - if (property0.NameEquals("numberOfChildren"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - numberOfChildren = null; - continue; - } - numberOfChildren = property0.Value.GetInt32(); - continue; - } - if (property0.NameEquals("numberOfChildGroups"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - numberOfChildGroups = null; - continue; - } - numberOfChildGroups = property0.Value.GetInt32(); - continue; - } - if (property0.NameEquals("parentDisplayNameChain"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - parentDisplayNameChain = null; - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - parentDisplayNameChain = array; - continue; - } - if (property0.NameEquals("parentNameChain"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - parentNameChain = null; - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - parentNameChain = array; - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new EntityData( - id, - name, - type, - systemData, - tenantId, - displayName, - parent, - permissions, - inheritedPermissions, - numberOfDescendants, - numberOfChildren, - numberOfChildGroups, - parentDisplayNameChain ?? new ChangeTrackingList(), - parentNameChain ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.Append(" properties:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TenantId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenantId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TenantId)) - { - builder.Append(" tenantId: "); - builder.AppendLine($"'{TenantId.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue("ParentId", out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parent: "); - builder.AppendLine("{"); - builder.AppendLine(" parent: {"); - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - builder.AppendLine(" }"); - builder.AppendLine(" }"); - } - else - { - if (Optional.IsDefined(Parent)) - { - builder.Append(" parent: "); - BicepSerializationHelpers.AppendChildObject(builder, Parent, options, 4, false, " parent: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Permissions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" permissions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Permissions)) - { - builder.Append(" permissions: "); - builder.AppendLine($"'{Permissions.Value.ToSerialString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(InheritedPermissions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" inheritedPermissions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(InheritedPermissions)) - { - builder.Append(" inheritedPermissions: "); - builder.AppendLine($"'{InheritedPermissions.Value.ToSerialString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NumberOfDescendants), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" numberOfDescendants: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NumberOfDescendants)) - { - builder.Append(" numberOfDescendants: "); - builder.AppendLine($"{NumberOfDescendants.Value}"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NumberOfChildren), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" numberOfChildren: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NumberOfChildren)) - { - builder.Append(" numberOfChildren: "); - builder.AppendLine($"{NumberOfChildren.Value}"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NumberOfChildGroups), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" numberOfChildGroups: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NumberOfChildGroups)) - { - builder.Append(" numberOfChildGroups: "); - builder.AppendLine($"{NumberOfChildGroups.Value}"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ParentDisplayNameChain), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parentDisplayNameChain: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ParentDisplayNameChain)) - { - if (ParentDisplayNameChain.Any()) - { - builder.Append(" parentDisplayNameChain: "); - builder.AppendLine("["); - foreach (var item in ParentDisplayNameChain) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ParentNameChain), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parentNameChain: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ParentNameChain)) - { - if (ParentNameChain.Any()) - { - builder.Append(" parentNameChain: "); - builder.AppendLine("["); - foreach (var item in ParentNameChain) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine(" }"); - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(EntityData)} does not support writing '{options.Format}' format."); - } - } - - EntityData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeEntityData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(EntityData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityData.cs deleted file mode 100644 index 08b09466be..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityData.cs +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The entity. - public partial class EntityData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal EntityData() - { - ParentDisplayNameChain = new ChangeTrackingList(); - ParentNameChain = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The AAD Tenant ID associated with the entity. For example, 00000000-0000-0000-0000-000000000000. - /// The friendly name of the management group. - /// (Optional) The ID of the parent management group. - /// The users specific permissions to this item. - /// The users specific permissions to this item. - /// Number of Descendants. - /// Number of children is the number of Groups and Subscriptions that are exactly one level underneath the current Group. - /// Number of children is the number of Groups that are exactly one level underneath the current Group. - /// The parent display name chain from the root group to the immediate parent. - /// The parent name chain from the root group to the immediate parent. - /// Keeps track of any properties unknown to the library. - internal EntityData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, Guid? tenantId, string displayName, SubResource parent, EntityPermission? permissions, EntityPermission? inheritedPermissions, int? numberOfDescendants, int? numberOfChildren, int? numberOfChildGroups, IReadOnlyList parentDisplayNameChain, IReadOnlyList parentNameChain, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - TenantId = tenantId; - DisplayName = displayName; - Parent = parent; - Permissions = permissions; - InheritedPermissions = inheritedPermissions; - NumberOfDescendants = numberOfDescendants; - NumberOfChildren = numberOfChildren; - NumberOfChildGroups = numberOfChildGroups; - ParentDisplayNameChain = parentDisplayNameChain; - ParentNameChain = parentNameChain; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The AAD Tenant ID associated with the entity. For example, 00000000-0000-0000-0000-000000000000. - [WirePath("properties.tenantId")] - public Guid? TenantId { get; } - /// The friendly name of the management group. - [WirePath("properties.displayName")] - public string DisplayName { get; } - /// (Optional) The ID of the parent management group. - internal SubResource Parent { get; } - /// Gets Id. - [WirePath("properties.parent.id")] - public ResourceIdentifier ParentId - { - get => Parent?.Id; - } - - /// The users specific permissions to this item. - [WirePath("properties.permissions")] - public EntityPermission? Permissions { get; } - /// The users specific permissions to this item. - [WirePath("properties.inheritedPermissions")] - public EntityPermission? InheritedPermissions { get; } - /// Number of Descendants. - [WirePath("properties.numberOfDescendants")] - public int? NumberOfDescendants { get; } - /// Number of children is the number of Groups and Subscriptions that are exactly one level underneath the current Group. - [WirePath("properties.numberOfChildren")] - public int? NumberOfChildren { get; } - /// Number of children is the number of Groups that are exactly one level underneath the current Group. - [WirePath("properties.numberOfChildGroups")] - public int? NumberOfChildGroups { get; } - /// The parent display name chain from the root group to the immediate parent. - [WirePath("properties.parentDisplayNameChain")] - public IReadOnlyList ParentDisplayNameChain { get; } - /// The parent name chain from the root group to the immediate parent. - [WirePath("properties.parentNameChain")] - public IReadOnlyList ParentNameChain { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityListResult.Serialization.cs deleted file mode 100644 index 8d9bf21e83..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityListResult.Serialization.cs +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - internal partial class EntityListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(EntityListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(Count)) - { - writer.WritePropertyName("count"u8); - writer.WriteNumberValue(Count.Value); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - EntityListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(EntityListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeEntityListResult(document.RootElement, options); - } - - internal static EntityListResult DeserializeEntityListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - int? count = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(EntityData.DeserializeEntityData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("count"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - count = property.Value.GetInt32(); - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new EntityListResult(value ?? new ChangeTrackingList(), count, nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Count), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" count: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Count)) - { - builder.Append(" count: "); - builder.AppendLine($"{Count.Value}"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(EntityListResult)} does not support writing '{options.Format}' format."); - } - } - - EntityListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeEntityListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(EntityListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityListResult.cs deleted file mode 100644 index 64d4927aa3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityListResult.cs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// Describes the result of the request to view entities. - internal partial class EntityListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal EntityListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The list of entities. - /// Total count of records that match the filter. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal EntityListResult(IReadOnlyList value, int? count, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - Count = count; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The list of entities. - public IReadOnlyList Value { get; } - /// Total count of records that match the filter. - public int? Count { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityPermission.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityPermission.Serialization.cs deleted file mode 100644 index a83caa1d91..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityPermission.Serialization.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - internal static partial class EntityPermissionExtensions - { - public static string ToSerialString(this EntityPermission value) => value switch - { - EntityPermission.NoAccess => "noaccess", - EntityPermission.View => "view", - EntityPermission.Edit => "edit", - EntityPermission.Delete => "delete", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown EntityPermission value.") - }; - - public static EntityPermission ToEntityPermission(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "noaccess")) return EntityPermission.NoAccess; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "view")) return EntityPermission.View; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "edit")) return EntityPermission.Edit; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "delete")) return EntityPermission.Delete; - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown EntityPermission value."); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityPermission.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityPermission.cs deleted file mode 100644 index c7a2a6c4cb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityPermission.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The users specific permissions to this item. - public enum EntityPermission - { - /// noaccess. - NoAccess, - /// view. - View, - /// edit. - Edit, - /// delete. - Delete - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntitySearchOption.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntitySearchOption.cs deleted file mode 100644 index f4893f29e1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntitySearchOption.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The EntitySearchOption. - public readonly partial struct EntitySearchOption : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public EntitySearchOption(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string AllowedParentsValue = "AllowedParents"; - private const string AllowedChildrenValue = "AllowedChildren"; - private const string ParentAndFirstLevelChildrenValue = "ParentAndFirstLevelChildren"; - private const string ParentOnlyValue = "ParentOnly"; - private const string ChildrenOnlyValue = "ChildrenOnly"; - - /// AllowedParents. - public static EntitySearchOption AllowedParents { get; } = new EntitySearchOption(AllowedParentsValue); - /// AllowedChildren. - public static EntitySearchOption AllowedChildren { get; } = new EntitySearchOption(AllowedChildrenValue); - /// ParentAndFirstLevelChildren. - public static EntitySearchOption ParentAndFirstLevelChildren { get; } = new EntitySearchOption(ParentAndFirstLevelChildrenValue); - /// ParentOnly. - public static EntitySearchOption ParentOnly { get; } = new EntitySearchOption(ParentOnlyValue); - /// ChildrenOnly. - public static EntitySearchOption ChildrenOnly { get; } = new EntitySearchOption(ChildrenOnlyValue); - /// Determines if two values are the same. - public static bool operator ==(EntitySearchOption left, EntitySearchOption right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(EntitySearchOption left, EntitySearchOption right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator EntitySearchOption(string value) => new EntitySearchOption(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is EntitySearchOption other && Equals(other); - /// - public bool Equals(EntitySearchOption other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityViewOption.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityViewOption.cs deleted file mode 100644 index d9b563079f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityViewOption.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The EntityViewOption. - public readonly partial struct EntityViewOption : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public EntityViewOption(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string FullHierarchyValue = "FullHierarchy"; - private const string GroupsOnlyValue = "GroupsOnly"; - private const string SubscriptionsOnlyValue = "SubscriptionsOnly"; - private const string AuditValue = "Audit"; - - /// FullHierarchy. - public static EntityViewOption FullHierarchy { get; } = new EntityViewOption(FullHierarchyValue); - /// GroupsOnly. - public static EntityViewOption GroupsOnly { get; } = new EntityViewOption(GroupsOnlyValue); - /// SubscriptionsOnly. - public static EntityViewOption SubscriptionsOnly { get; } = new EntityViewOption(SubscriptionsOnlyValue); - /// Audit. - public static EntityViewOption Audit { get; } = new EntityViewOption(AuditValue); - /// Determines if two values are the same. - public static bool operator ==(EntityViewOption left, EntityViewOption right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(EntityViewOption left, EntityViewOption right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator EntityViewOption(string value) => new EntityViewOption(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is EntityViewOption other && Equals(other); - /// - public bool Equals(EntityViewOption other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.Serialization.cs deleted file mode 100644 index b55f51fb8d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - internal partial class ListSubscriptionUnderManagementGroup : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ListSubscriptionUnderManagementGroup)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ListSubscriptionUnderManagementGroup IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ListSubscriptionUnderManagementGroup)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeListSubscriptionUnderManagementGroup(document.RootElement, options); - } - - internal static ListSubscriptionUnderManagementGroup DeserializeListSubscriptionUnderManagementGroup(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ManagementGroupSubscriptionData.DeserializeManagementGroupSubscriptionData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ListSubscriptionUnderManagementGroup(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ListSubscriptionUnderManagementGroup)} does not support writing '{options.Format}' format."); - } - } - - ListSubscriptionUnderManagementGroup IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeListSubscriptionUnderManagementGroup(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ListSubscriptionUnderManagementGroup)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.cs deleted file mode 100644 index 2b3b56a128..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The details of all subscriptions under management group. - internal partial class ListSubscriptionUnderManagementGroup - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ListSubscriptionUnderManagementGroup() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The list of subscriptions. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal ListSubscriptionUnderManagementGroup(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The list of subscriptions. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildInfo.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildInfo.Serialization.cs deleted file mode 100644 index 7ce933f5fc..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildInfo.Serialization.cs +++ /dev/null @@ -1,308 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupChildInfo : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupChildInfo)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(ChildType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ChildType.Value.ToString()); - } - if (Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (Optional.IsCollectionDefined(Children)) - { - writer.WritePropertyName("children"u8); - writer.WriteStartArray(); - foreach (var item in Children) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ManagementGroupChildInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupChildInfo)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupChildInfo(document.RootElement, options); - } - - internal static ManagementGroupChildInfo DeserializeManagementGroupChildInfo(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ManagementGroupChildType? type = default; - string id = default; - string name = default; - string displayName = default; - IReadOnlyList children = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = new ManagementGroupChildType(property.Value.GetString()); - continue; - } - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (property.NameEquals("children"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(DeserializeManagementGroupChildInfo(item, options)); - } - children = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupChildInfo( - type, - id, - name, - displayName, - children ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - if (Id.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Id}'''"); - } - else - { - builder.AppendLine($"'{Id}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Children), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" children: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Children)) - { - if (Children.Any()) - { - builder.Append(" children: "); - builder.AppendLine("["); - foreach (var item in Children) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " children: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementGroupChildInfo)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupChildInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupChildInfo(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupChildInfo)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildInfo.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildInfo.cs deleted file mode 100644 index 57e19925e0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildInfo.cs +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The child information of a management group. - public partial class ManagementGroupChildInfo - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagementGroupChildInfo() - { - Children = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The fully qualified resource type which includes provider namespace (e.g. Microsoft.Management/managementGroups). - /// The fully qualified ID for the child resource (management group or subscription). For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The name of the child entity. - /// The friendly name of the child resource. - /// The list of children. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupChildInfo(ManagementGroupChildType? childType, string id, string name, string displayName, IReadOnlyList children, IDictionary serializedAdditionalRawData) - { - ChildType = childType; - Id = id; - Name = name; - DisplayName = displayName; - Children = children; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The fully qualified resource type which includes provider namespace (e.g. Microsoft.Management/managementGroups). - [WirePath("type")] - public ManagementGroupChildType? ChildType { get; } - /// The fully qualified ID for the child resource (management group or subscription). For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - [WirePath("id")] - public string Id { get; } - /// The name of the child entity. - [WirePath("name")] - public string Name { get; } - /// The friendly name of the child resource. - [WirePath("displayName")] - public string DisplayName { get; } - /// The list of children. - [WirePath("children")] - public IReadOnlyList Children { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildOptions.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildOptions.Serialization.cs deleted file mode 100644 index daf08773ac..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildOptions.Serialization.cs +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupChildOptions : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupChildOptions)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(ChildType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ChildType.Value.ToString()); - } - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (options.Format != "W" && Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (options.Format != "W" && Optional.IsCollectionDefined(Children)) - { - writer.WritePropertyName("children"u8); - writer.WriteStartArray(); - foreach (var item in Children) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ManagementGroupChildOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupChildOptions)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupChildOptions(document.RootElement, options); - } - - internal static ManagementGroupChildOptions DeserializeManagementGroupChildOptions(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ManagementGroupChildType? type = default; - string id = default; - string name = default; - string displayName = default; - IReadOnlyList children = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = new ManagementGroupChildType(property.Value.GetString()); - continue; - } - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (property.NameEquals("children"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(DeserializeManagementGroupChildOptions(item, options)); - } - children = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupChildOptions( - type, - id, - name, - displayName, - children ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ManagementGroupChildOptions)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupChildOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupChildOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupChildOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildOptions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildOptions.cs deleted file mode 100644 index fa5796a8fe..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildOptions.cs +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The child information of a management group used during creation. - public partial class ManagementGroupChildOptions - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagementGroupChildOptions() - { - Children = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The fully qualified resource type which includes provider namespace (e.g. Microsoft.Management/managementGroups). - /// The fully qualified ID for the child resource (management group or subscription). For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The name of the child entity. - /// The friendly name of the child resource. - /// The list of children. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupChildOptions(ManagementGroupChildType? childType, string id, string name, string displayName, IReadOnlyList children, IDictionary serializedAdditionalRawData) - { - ChildType = childType; - Id = id; - Name = name; - DisplayName = displayName; - Children = children; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The fully qualified resource type which includes provider namespace (e.g. Microsoft.Management/managementGroups). - [WirePath("type")] - public ManagementGroupChildType? ChildType { get; } - /// The fully qualified ID for the child resource (management group or subscription). For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - [WirePath("id")] - public string Id { get; } - /// The name of the child entity. - [WirePath("name")] - public string Name { get; } - /// The friendly name of the child resource. - [WirePath("displayName")] - public string DisplayName { get; } - /// The list of children. - [WirePath("children")] - public IReadOnlyList Children { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildType.cs deleted file mode 100644 index 75e6a37c4a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildType.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The type of child resource. - public readonly partial struct ManagementGroupChildType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ManagementGroupChildType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string MicrosoftManagementManagementGroupsValue = "Microsoft.Management/managementGroups"; - private const string SubscriptionsValue = "/subscriptions"; - - /// Microsoft.Management/managementGroups. - public static ManagementGroupChildType MicrosoftManagementManagementGroups { get; } = new ManagementGroupChildType(MicrosoftManagementManagementGroupsValue); - /// /subscriptions. - public static ManagementGroupChildType Subscriptions { get; } = new ManagementGroupChildType(SubscriptionsValue); - /// Determines if two values are the same. - public static bool operator ==(ManagementGroupChildType left, ManagementGroupChildType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ManagementGroupChildType left, ManagementGroupChildType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ManagementGroupChildType(string value) => new ManagementGroupChildType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ManagementGroupChildType other && Equals(other); - /// - public bool Equals(ManagementGroupChildType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCollectionGetEntitiesOptions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCollectionGetEntitiesOptions.cs deleted file mode 100644 index 3fc2633c8a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCollectionGetEntitiesOptions.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The ManagementGroupCollectionGetEntitiesOptions. - public partial class ManagementGroupCollectionGetEntitiesOptions - { - /// Initializes a new instance of . - public ManagementGroupCollectionGetEntitiesOptions() - { - } - - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - [WirePath("skipToken")] - public string SkipToken { get; set; } - /// Number of entities to skip over when retrieving results. Passing this in will override $skipToken. - [WirePath("skip")] - public int? Skip { get; set; } - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - [WirePath("top")] - public int? Top { get; set; } - /// This parameter specifies the fields to include in the response. Can include any combination of Name,DisplayName,Type,ParentDisplayNameChain,ParentChain, e.g. '$select=Name,DisplayName,Type,ParentDisplayNameChain,ParentNameChain'. When specified the $select parameter can override select in $skipToken. - [WirePath("select")] - public string Select { get; set; } - /// - /// The $search parameter is used in conjunction with the $filter parameter to return three different outputs depending on the parameter passed in. - /// With $search=AllowedParents the API will return the entity info of all groups that the requested entity will be able to reparent to as determined by the user's permissions. - /// With $search=AllowedChildren the API will return the entity info of all entities that can be added as children of the requested entity. - /// With $search=ParentAndFirstLevelChildren the API will return the parent and first level of children that the user has either direct access to or indirect access via one of their descendants. - /// With $search=ParentOnly the API will return only the group if the user has access to at least one of the descendants of the group. - /// With $search=ChildrenOnly the API will return only the first level of children of the group entity info specified in $filter. The user must have direct access to the children entities or one of it's descendants for it to show up in the results. - /// - [WirePath("search")] - public EntitySearchOption? Search { get; set; } - /// The filter parameter allows you to filter on the the name or display name fields. You can check for equality on the name field (e.g. name eq '{entityName}') and you can check for substrings on either the name or display name fields(e.g. contains(name, '{substringToSearch}'), contains(displayName, '{substringToSearch')). Note that the '{entityName}' and '{substringToSearch}' fields are checked case insensitively. - [WirePath("filter")] - public string Filter { get; set; } - /// The view parameter allows clients to filter the type of data that is returned by the getEntities call. - [WirePath("view")] - public EntityViewOption? View { get; set; } - /// A filter which allows the get entities call to focus on a particular group (i.e. "$filter=name eq 'groupName'"). - [WirePath("groupName")] - public string GroupName { get; set; } - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - [WirePath("cacheControl")] - public string CacheControl { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.Serialization.cs deleted file mode 100644 index b085a0a218..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.Serialization.cs +++ /dev/null @@ -1,264 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupCreateOrUpdateContent : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupCreateOrUpdateContent)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && Optional.IsDefined(ResourceType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ResourceType.Value); - } - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (options.Format != "W" && Optional.IsDefined(TenantId)) - { - writer.WritePropertyName("tenantId"u8); - writer.WriteStringValue(TenantId.Value); - } - if (Optional.IsDefined(DisplayName)) - { - if (DisplayName != null) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - else - { - writer.WriteNull("displayName"); - } - } - if (Optional.IsDefined(Details)) - { - writer.WritePropertyName("details"u8); - writer.WriteObjectValue(Details, options); - } - if (options.Format != "W" && Optional.IsCollectionDefined(Children)) - { - if (Children != null) - { - writer.WritePropertyName("children"u8); - writer.WriteStartArray(); - foreach (var item in Children) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - else - { - writer.WriteNull("children"); - } - } - writer.WriteEndObject(); - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ManagementGroupCreateOrUpdateContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupCreateOrUpdateContent)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupCreateOrUpdateContent(document.RootElement, options); - } - - internal static ManagementGroupCreateOrUpdateContent DeserializeManagementGroupCreateOrUpdateContent(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string id = default; - ResourceType? type = default; - string name = default; - Guid? tenantId = default; - string displayName = default; - CreateManagementGroupDetails details = default; - IReadOnlyList children = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("tenantId"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - tenantId = property0.Value.GetGuid(); - continue; - } - if (property0.NameEquals("displayName"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - displayName = null; - continue; - } - displayName = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("details"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - details = CreateManagementGroupDetails.DeserializeCreateManagementGroupDetails(property0.Value, options); - continue; - } - if (property0.NameEquals("children"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - children = null; - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(ManagementGroupChildOptions.DeserializeManagementGroupChildOptions(item, options)); - } - children = array; - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupCreateOrUpdateContent( - id, - type, - name, - tenantId, - displayName, - details, - children ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ManagementGroupCreateOrUpdateContent)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupCreateOrUpdateContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupCreateOrUpdateContent(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupCreateOrUpdateContent)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.cs deleted file mode 100644 index 079151fec3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.cs +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// Management group creation parameters. - public partial class ManagementGroupCreateOrUpdateContent - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ManagementGroupCreateOrUpdateContent() - { - Children = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The type of the resource. For example, Microsoft.Management/managementGroups. - /// The name of the management group. For example, 00000000-0000-0000-0000-000000000000. - /// The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000. - /// The friendly name of the management group. If no value is passed then this field will be set to the groupId. - /// The details of a management group used during creation. - /// The list of children. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupCreateOrUpdateContent(string id, ResourceType? resourceType, string name, Guid? tenantId, string displayName, CreateManagementGroupDetails details, IReadOnlyList children, IDictionary serializedAdditionalRawData) - { - Id = id; - ResourceType = resourceType; - Name = name; - TenantId = tenantId; - DisplayName = displayName; - Details = details; - Children = children; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - [WirePath("id")] - public string Id { get; } - /// The type of the resource. For example, Microsoft.Management/managementGroups. - [WirePath("type")] - public ResourceType? ResourceType { get; } - /// The name of the management group. For example, 00000000-0000-0000-0000-000000000000. - [WirePath("name")] - public string Name { get; set; } - /// The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000. - [WirePath("properties.tenantId")] - public Guid? TenantId { get; } - /// The friendly name of the management group. If no value is passed then this field will be set to the groupId. - [WirePath("properties.displayName")] - public string DisplayName { get; set; } - /// The details of a management group used during creation. - [WirePath("properties.details")] - public CreateManagementGroupDetails Details { get; set; } - /// The list of children. - [WirePath("properties.children")] - public IReadOnlyList Children { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupExpandType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupExpandType.cs deleted file mode 100644 index 6fd33fdd70..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupExpandType.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The ManagementGroupExpandType. - public readonly partial struct ManagementGroupExpandType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ManagementGroupExpandType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string ChildrenValue = "children"; - private const string PathValue = "path"; - private const string AncestorsValue = "ancestors"; - - /// children. - public static ManagementGroupExpandType Children { get; } = new ManagementGroupExpandType(ChildrenValue); - /// path. - public static ManagementGroupExpandType Path { get; } = new ManagementGroupExpandType(PathValue); - /// ancestors. - public static ManagementGroupExpandType Ancestors { get; } = new ManagementGroupExpandType(AncestorsValue); - /// Determines if two values are the same. - public static bool operator ==(ManagementGroupExpandType left, ManagementGroupExpandType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ManagementGroupExpandType left, ManagementGroupExpandType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ManagementGroupExpandType(string value) => new ManagementGroupExpandType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ManagementGroupExpandType other && Equals(other); - /// - public bool Equals(ManagementGroupExpandType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupInfo.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupInfo.Serialization.cs deleted file mode 100644 index 0428a7dd86..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupInfo.Serialization.cs +++ /dev/null @@ -1,451 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupInfo : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupInfo)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Version)) - { - writer.WritePropertyName("version"u8); - writer.WriteNumberValue(Version.Value); - } - if (Optional.IsDefined(UpdatedOn)) - { - writer.WritePropertyName("updatedTime"u8); - writer.WriteStringValue(UpdatedOn.Value, "O"); - } - if (Optional.IsDefined(UpdatedBy)) - { - writer.WritePropertyName("updatedBy"u8); - writer.WriteStringValue(UpdatedBy); - } - if (Optional.IsDefined(Parent)) - { - writer.WritePropertyName("parent"u8); - writer.WriteObjectValue(Parent, options); - } - if (Optional.IsCollectionDefined(Path)) - { - if (Path != null) - { - writer.WritePropertyName("path"u8); - writer.WriteStartArray(); - foreach (var item in Path) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - else - { - writer.WriteNull("path"); - } - } - if (Optional.IsCollectionDefined(ManagementGroupAncestors)) - { - if (ManagementGroupAncestors != null) - { - writer.WritePropertyName("managementGroupAncestors"u8); - writer.WriteStartArray(); - foreach (var item in ManagementGroupAncestors) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - else - { - writer.WriteNull("managementGroupAncestors"); - } - } - if (Optional.IsCollectionDefined(ManagementGroupAncestorChain)) - { - if (ManagementGroupAncestorChain != null) - { - writer.WritePropertyName("managementGroupAncestorsChain"u8); - writer.WriteStartArray(); - foreach (var item in ManagementGroupAncestorChain) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - else - { - writer.WriteNull("managementGroupAncestorsChain"); - } - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ManagementGroupInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupInfo)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupInfo(document.RootElement, options); - } - - internal static ManagementGroupInfo DeserializeManagementGroupInfo(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - int? version = default; - DateTimeOffset? updatedTime = default; - string updatedBy = default; - ParentManagementGroupInfo parent = default; - IReadOnlyList path = default; - IReadOnlyList managementGroupAncestors = default; - IReadOnlyList managementGroupAncestorsChain = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("version"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - version = property.Value.GetInt32(); - continue; - } - if (property.NameEquals("updatedTime"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - updatedTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("updatedBy"u8)) - { - updatedBy = property.Value.GetString(); - continue; - } - if (property.NameEquals("parent"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - parent = ParentManagementGroupInfo.DeserializeParentManagementGroupInfo(property.Value, options); - continue; - } - if (property.NameEquals("path"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - path = null; - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ManagementGroupPathElement.DeserializeManagementGroupPathElement(item, options)); - } - path = array; - continue; - } - if (property.NameEquals("managementGroupAncestors"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - managementGroupAncestors = null; - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - managementGroupAncestors = array; - continue; - } - if (property.NameEquals("managementGroupAncestorsChain"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - managementGroupAncestorsChain = null; - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ManagementGroupPathElement.DeserializeManagementGroupPathElement(item, options)); - } - managementGroupAncestorsChain = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupInfo( - version, - updatedTime, - updatedBy, - parent, - path ?? new ChangeTrackingList(), - managementGroupAncestors ?? new ChangeTrackingList(), - managementGroupAncestorsChain ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Version), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" version: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Version)) - { - builder.Append(" version: "); - builder.AppendLine($"{Version.Value}"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(UpdatedOn), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" updatedTime: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(UpdatedOn)) - { - builder.Append(" updatedTime: "); - var formattedDateTimeString = TypeFormatters.ToString(UpdatedOn.Value, "o"); - builder.AppendLine($"'{formattedDateTimeString}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(UpdatedBy), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" updatedBy: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(UpdatedBy)) - { - builder.Append(" updatedBy: "); - if (UpdatedBy.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{UpdatedBy}'''"); - } - else - { - builder.AppendLine($"'{UpdatedBy}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Parent), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parent: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Parent)) - { - builder.Append(" parent: "); - BicepSerializationHelpers.AppendChildObject(builder, Parent, options, 2, false, " parent: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Path), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" path: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Path)) - { - if (Path.Any()) - { - builder.Append(" path: "); - builder.AppendLine("["); - foreach (var item in Path) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " path: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ManagementGroupAncestors), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" managementGroupAncestors: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ManagementGroupAncestors)) - { - if (ManagementGroupAncestors.Any()) - { - builder.Append(" managementGroupAncestors: "); - builder.AppendLine("["); - foreach (var item in ManagementGroupAncestors) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ManagementGroupAncestorChain), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" managementGroupAncestorsChain: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ManagementGroupAncestorChain)) - { - if (ManagementGroupAncestorChain.Any()) - { - builder.Append(" managementGroupAncestorsChain: "); - builder.AppendLine("["); - foreach (var item in ManagementGroupAncestorChain) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " managementGroupAncestorsChain: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementGroupInfo)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupInfo(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupInfo)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupInfo.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupInfo.cs deleted file mode 100644 index 05985dbcf7..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupInfo.cs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The details of a management group. - public partial class ManagementGroupInfo - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagementGroupInfo() - { - Path = new ChangeTrackingList(); - ManagementGroupAncestors = new ChangeTrackingList(); - ManagementGroupAncestorChain = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The version number of the object. - /// The date and time when this object was last updated. - /// The identity of the principal or process that updated the object. - /// (Optional) The ID of the parent management group. - /// The path from the root to the current group. - /// The ancestors of the management group. - /// The ancestors of the management group displayed in reversed order, from immediate parent to the root. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupInfo(int? version, DateTimeOffset? updatedOn, string updatedBy, ParentManagementGroupInfo parent, IReadOnlyList path, IReadOnlyList managementGroupAncestors, IReadOnlyList managementGroupAncestorChain, IDictionary serializedAdditionalRawData) - { - Version = version; - UpdatedOn = updatedOn; - UpdatedBy = updatedBy; - Parent = parent; - Path = path; - ManagementGroupAncestors = managementGroupAncestors; - ManagementGroupAncestorChain = managementGroupAncestorChain; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The version number of the object. - [WirePath("version")] - public int? Version { get; } - /// The date and time when this object was last updated. - [WirePath("updatedTime")] - public DateTimeOffset? UpdatedOn { get; } - /// The identity of the principal or process that updated the object. - [WirePath("updatedBy")] - public string UpdatedBy { get; } - /// (Optional) The ID of the parent management group. - [WirePath("parent")] - public ParentManagementGroupInfo Parent { get; } - /// The path from the root to the current group. - [WirePath("path")] - public IReadOnlyList Path { get; } - /// The ancestors of the management group. - [WirePath("managementGroupAncestors")] - public IReadOnlyList ManagementGroupAncestors { get; } - /// The ancestors of the management group displayed in reversed order, from immediate parent to the root. - [WirePath("managementGroupAncestorsChain")] - public IReadOnlyList ManagementGroupAncestorChain { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupListResult.Serialization.cs deleted file mode 100644 index 93f35bd07d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - internal partial class ManagementGroupListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("@nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ManagementGroupListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupListResult(document.RootElement, options); - } - - internal static ManagementGroupListResult DeserializeManagementGroupListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ManagementGroupData.DeserializeManagementGroupData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("@nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" @nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" @nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementGroupListResult)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupListResult.cs deleted file mode 100644 index 814cf13d89..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// Describes the result of the request to list management groups. - internal partial class ManagementGroupListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagementGroupListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The list of management groups. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The list of management groups. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.Serialization.cs deleted file mode 100644 index f7242a4883..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.Serialization.cs +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupNameAvailabilityContent : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupNameAvailabilityContent)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(ResourceType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ResourceType.Value); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ManagementGroupNameAvailabilityContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupNameAvailabilityContent)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupNameAvailabilityContent(document.RootElement, options); - } - - internal static ManagementGroupNameAvailabilityContent DeserializeManagementGroupNameAvailabilityContent(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - ResourceType? type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = new ResourceType(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupNameAvailabilityContent(name, type, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ManagementGroupNameAvailabilityContent)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupNameAvailabilityContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupNameAvailabilityContent(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupNameAvailabilityContent)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.cs deleted file mode 100644 index cbe681771f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.cs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// Management group name availability check parameters. - public partial class ManagementGroupNameAvailabilityContent - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// the name to check for availability. - /// fully qualified resource type which includes provider namespace. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupNameAvailabilityContent(string name, ResourceType? resourceType, IDictionary serializedAdditionalRawData) - { - Name = name; - ResourceType = resourceType; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// the name to check for availability. - [WirePath("name")] - public string Name { get; set; } - /// fully qualified resource type which includes provider namespace. - [WirePath("type")] - public ResourceType? ResourceType { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.Serialization.cs deleted file mode 100644 index 4b5dae992e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.Serialization.cs +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupNameAvailabilityResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupNameAvailabilityResult)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(NameAvailable)) - { - writer.WritePropertyName("nameAvailable"u8); - writer.WriteBooleanValue(NameAvailable.Value); - } - if (options.Format != "W" && Optional.IsDefined(Reason)) - { - writer.WritePropertyName("reason"u8); - writer.WriteStringValue(Reason.Value.ToSerialString()); - } - if (options.Format != "W" && Optional.IsDefined(Message)) - { - writer.WritePropertyName("message"u8); - writer.WriteStringValue(Message); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ManagementGroupNameAvailabilityResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupNameAvailabilityResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupNameAvailabilityResult(document.RootElement, options); - } - - internal static ManagementGroupNameAvailabilityResult DeserializeManagementGroupNameAvailabilityResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - bool? nameAvailable = default; - ManagementGroupNameUnavailableReason? reason = default; - string message = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("nameAvailable"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - nameAvailable = property.Value.GetBoolean(); - continue; - } - if (property.NameEquals("reason"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - reason = property.Value.GetString().ToManagementGroupNameUnavailableReason(); - continue; - } - if (property.NameEquals("message"u8)) - { - message = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupNameAvailabilityResult(nameAvailable, reason, message, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NameAvailable), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nameAvailable: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NameAvailable)) - { - builder.Append(" nameAvailable: "); - var boolValue = NameAvailable.Value == true ? "true" : "false"; - builder.AppendLine($"{boolValue}"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Reason), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" reason: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Reason)) - { - builder.Append(" reason: "); - builder.AppendLine($"'{Reason.Value.ToSerialString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Message), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" message: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Message)) - { - builder.Append(" message: "); - if (Message.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Message}'''"); - } - else - { - builder.AppendLine($"'{Message}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementGroupNameAvailabilityResult)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupNameAvailabilityResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupNameAvailabilityResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupNameAvailabilityResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.cs deleted file mode 100644 index 1c2a592629..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// Describes the result of the request to check management group name availability. - public partial class ManagementGroupNameAvailabilityResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagementGroupNameAvailabilityResult() - { - } - - /// Initializes a new instance of . - /// Required. True indicates name is valid and available. False indicates the name is invalid, unavailable, or both. - /// Required if nameAvailable == false. Invalid indicates the name provided does not match the resource provider's naming requirements (incorrect length, unsupported characters, etc.) AlreadyExists indicates that the name is already in use and is therefore unavailable. - /// Required if nameAvailable == false. Localized. If reason == invalid, provide the user with the reason why the given name is invalid, and provide the resource naming requirements so that the user can select a valid name. If reason == AlreadyExists, explain that is already in use, and direct them to select a different name. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupNameAvailabilityResult(bool? nameAvailable, ManagementGroupNameUnavailableReason? reason, string message, IDictionary serializedAdditionalRawData) - { - NameAvailable = nameAvailable; - Reason = reason; - Message = message; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Required. True indicates name is valid and available. False indicates the name is invalid, unavailable, or both. - [WirePath("nameAvailable")] - public bool? NameAvailable { get; } - /// Required if nameAvailable == false. Invalid indicates the name provided does not match the resource provider's naming requirements (incorrect length, unsupported characters, etc.) AlreadyExists indicates that the name is already in use and is therefore unavailable. - [WirePath("reason")] - public ManagementGroupNameUnavailableReason? Reason { get; } - /// Required if nameAvailable == false. Localized. If reason == invalid, provide the user with the reason why the given name is invalid, and provide the resource naming requirements so that the user can select a valid name. If reason == AlreadyExists, explain that is already in use, and direct them to select a different name. - [WirePath("message")] - public string Message { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.Serialization.cs deleted file mode 100644 index 682fa73fb9..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.Serialization.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - internal static partial class ManagementGroupNameUnavailableReasonExtensions - { - public static string ToSerialString(this ManagementGroupNameUnavailableReason value) => value switch - { - ManagementGroupNameUnavailableReason.Invalid => "Invalid", - ManagementGroupNameUnavailableReason.AlreadyExists => "AlreadyExists", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ManagementGroupNameUnavailableReason value.") - }; - - public static ManagementGroupNameUnavailableReason ToManagementGroupNameUnavailableReason(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Invalid")) return ManagementGroupNameUnavailableReason.Invalid; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "AlreadyExists")) return ManagementGroupNameUnavailableReason.AlreadyExists; - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ManagementGroupNameUnavailableReason value."); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.cs deleted file mode 100644 index 71cedf1e26..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// Required if nameAvailable == false. Invalid indicates the name provided does not match the resource provider's naming requirements (incorrect length, unsupported characters, etc.) AlreadyExists indicates that the name is already in use and is therefore unavailable. - public enum ManagementGroupNameUnavailableReason - { - /// Invalid. - Invalid, - /// AlreadyExists. - AlreadyExists - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.Serialization.cs deleted file mode 100644 index dc28ce4978..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.Serialization.cs +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupParentCreateOptions : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupParentCreateOptions)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (options.Format != "W" && Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ManagementGroupParentCreateOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupParentCreateOptions)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupParentCreateOptions(document.RootElement, options); - } - - internal static ManagementGroupParentCreateOptions DeserializeManagementGroupParentCreateOptions(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string id = default; - string name = default; - string displayName = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupParentCreateOptions(id, name, displayName, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ManagementGroupParentCreateOptions)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupParentCreateOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupParentCreateOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupParentCreateOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.cs deleted file mode 100644 index 13e65d6bf7..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// (Optional) The ID of the parent management group used during creation. - public partial class ManagementGroupParentCreateOptions - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ManagementGroupParentCreateOptions() - { - } - - /// Initializes a new instance of . - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The name of the parent management group. - /// The friendly name of the parent management group. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupParentCreateOptions(string id, string name, string displayName, IDictionary serializedAdditionalRawData) - { - Id = id; - Name = name; - DisplayName = displayName; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - [WirePath("id")] - public string Id { get; set; } - /// The name of the parent management group. - [WirePath("name")] - public string Name { get; } - /// The friendly name of the parent management group. - [WirePath("displayName")] - public string DisplayName { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPatch.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPatch.Serialization.cs deleted file mode 100644 index b3b7c7b454..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPatch.Serialization.cs +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupPatch : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupPatch)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(DisplayName)) - { - if (DisplayName != null) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - else - { - writer.WriteNull("displayName"); - } - } - if (Optional.IsDefined(ParentGroupId)) - { - if (ParentGroupId != null) - { - writer.WritePropertyName("parentGroupId"u8); - writer.WriteStringValue(ParentGroupId); - } - else - { - writer.WriteNull("parentGroupId"); - } - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ManagementGroupPatch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupPatch)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupPatch(document.RootElement, options); - } - - internal static ManagementGroupPatch DeserializeManagementGroupPatch(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string displayName = default; - string parentGroupId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("displayName"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - displayName = null; - continue; - } - displayName = property.Value.GetString(); - continue; - } - if (property.NameEquals("parentGroupId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - parentGroupId = null; - continue; - } - parentGroupId = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupPatch(displayName, parentGroupId, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ManagementGroupPatch)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupPatch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupPatch(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupPatch)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPatch.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPatch.cs deleted file mode 100644 index 8d3aeabcf3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPatch.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// Management group patch parameters. - public partial class ManagementGroupPatch - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ManagementGroupPatch() - { - } - - /// Initializes a new instance of . - /// The friendly name of the management group. - /// (Optional) The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupPatch(string displayName, string parentGroupId, IDictionary serializedAdditionalRawData) - { - DisplayName = displayName; - ParentGroupId = parentGroupId; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The friendly name of the management group. - [WirePath("displayName")] - public string DisplayName { get; set; } - /// (Optional) The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - [WirePath("parentGroupId")] - public string ParentGroupId { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPathElement.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPathElement.Serialization.cs deleted file mode 100644 index f43d095d7d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPathElement.Serialization.cs +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupPathElement : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupPathElement)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ManagementGroupPathElement IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupPathElement)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupPathElement(document.RootElement, options); - } - - internal static ManagementGroupPathElement DeserializeManagementGroupPathElement(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - string displayName = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupPathElement(name, displayName, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementGroupPathElement)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupPathElement IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupPathElement(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupPathElement)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPathElement.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPathElement.cs deleted file mode 100644 index 83a547b41a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPathElement.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// A path element of a management group ancestors. - public partial class ManagementGroupPathElement - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagementGroupPathElement() - { - } - - /// Initializes a new instance of . - /// The name of the group. - /// The friendly name of the group. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupPathElement(string name, string displayName, IDictionary serializedAdditionalRawData) - { - Name = name; - DisplayName = displayName; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The name of the group. - [WirePath("name")] - public string Name { get; } - /// The friendly name of the group. - [WirePath("displayName")] - public string DisplayName { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ParentManagementGroupInfo.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ParentManagementGroupInfo.Serialization.cs deleted file mode 100644 index 83195e73cf..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ParentManagementGroupInfo.Serialization.cs +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ParentManagementGroupInfo : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ParentManagementGroupInfo)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ParentManagementGroupInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ParentManagementGroupInfo)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeParentManagementGroupInfo(document.RootElement, options); - } - - internal static ParentManagementGroupInfo DeserializeParentManagementGroupInfo(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string id = default; - string name = default; - string displayName = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ParentManagementGroupInfo(id, name, displayName, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - if (Id.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Id}'''"); - } - else - { - builder.AppendLine($"'{Id}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ParentManagementGroupInfo)} does not support writing '{options.Format}' format."); - } - } - - ParentManagementGroupInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeParentManagementGroupInfo(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ParentManagementGroupInfo)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ParentManagementGroupInfo.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ParentManagementGroupInfo.cs deleted file mode 100644 index 910a28524a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ParentManagementGroupInfo.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// (Optional) The ID of the parent management group. - public partial class ParentManagementGroupInfo - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ParentManagementGroupInfo() - { - } - - /// Initializes a new instance of . - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The name of the parent management group. - /// The friendly name of the parent management group. - /// Keeps track of any properties unknown to the library. - internal ParentManagementGroupInfo(string id, string name, string displayName, IDictionary serializedAdditionalRawData) - { - Id = id; - Name = name; - DisplayName = displayName; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - [WirePath("id")] - public string Id { get; } - /// The name of the parent management group. - [WirePath("name")] - public string Name { get; } - /// The friendly name of the parent management group. - [WirePath("displayName")] - public string DisplayName { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ResourceManagerModelFactory.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ResourceManagerModelFactory.cs deleted file mode 100644 index 71c0f3315e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/ResourceManagerModelFactory.cs +++ /dev/null @@ -1,269 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Linq; -using Azure.Core; -using Azure.ResourceManager.ManagementGroups; -using Azure.ResourceManager.ManagementGroups.Models; - -namespace Azure.ResourceManager.Models -{ - /// Model factory for models. - public static partial class ResourceManagerModelFactory - { - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000. - /// The friendly name of the management group. - /// The details of a management group. - /// The list of children. - /// A new instance for mocking. - public static ManagementGroupData ManagementGroupData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, Guid? tenantId = null, string displayName = null, ManagementGroupInfo details = null, IEnumerable children = null) - { - children ??= new List(); - - return new ManagementGroupData( - id, - name, - resourceType, - systemData, - tenantId, - displayName, - details, - children?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The version number of the object. - /// The date and time when this object was last updated. - /// The identity of the principal or process that updated the object. - /// (Optional) The ID of the parent management group. - /// The path from the root to the current group. - /// The ancestors of the management group. - /// The ancestors of the management group displayed in reversed order, from immediate parent to the root. - /// A new instance for mocking. - public static ManagementGroupInfo ManagementGroupInfo(int? version = null, DateTimeOffset? updatedOn = null, string updatedBy = null, ParentManagementGroupInfo parent = null, IEnumerable path = null, IEnumerable managementGroupAncestors = null, IEnumerable managementGroupAncestorChain = null) - { - path ??= new List(); - managementGroupAncestors ??= new List(); - managementGroupAncestorChain ??= new List(); - - return new ManagementGroupInfo( - version, - updatedOn, - updatedBy, - parent, - path?.ToList(), - managementGroupAncestors?.ToList(), - managementGroupAncestorChain?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The name of the parent management group. - /// The friendly name of the parent management group. - /// A new instance for mocking. - public static ParentManagementGroupInfo ParentManagementGroupInfo(string id = null, string name = null, string displayName = null) - { - return new ParentManagementGroupInfo(id, name, displayName, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The name of the group. - /// The friendly name of the group. - /// A new instance for mocking. - public static ManagementGroupPathElement ManagementGroupPathElement(string name = null, string displayName = null) - { - return new ManagementGroupPathElement(name, displayName, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The fully qualified resource type which includes provider namespace (e.g. Microsoft.Management/managementGroups). - /// The fully qualified ID for the child resource (management group or subscription). For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The name of the child entity. - /// The friendly name of the child resource. - /// The list of children. - /// A new instance for mocking. - public static ManagementGroupChildInfo ManagementGroupChildInfo(ManagementGroupChildType? childType = null, string id = null, string name = null, string displayName = null, IEnumerable children = null) - { - children ??= new List(); - - return new ManagementGroupChildInfo( - childType, - id, - name, - displayName, - children?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The type of the resource. For example, Microsoft.Management/managementGroups. - /// The name of the management group. For example, 00000000-0000-0000-0000-000000000000. - /// The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000. - /// The friendly name of the management group. If no value is passed then this field will be set to the groupId. - /// The details of a management group used during creation. - /// The list of children. - /// A new instance for mocking. - public static ManagementGroupCreateOrUpdateContent ManagementGroupCreateOrUpdateContent(string id = null, ResourceType? resourceType = null, string name = null, Guid? tenantId = null, string displayName = null, CreateManagementGroupDetails details = null, IEnumerable children = null) - { - children ??= new List(); - - return new ManagementGroupCreateOrUpdateContent( - id, - resourceType, - name, - tenantId, - displayName, - details, - children?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The version number of the object. - /// The date and time when this object was last updated. - /// The identity of the principal or process that updated the object. - /// (Optional) The ID of the parent management group used during creation. - /// A new instance for mocking. - public static CreateManagementGroupDetails CreateManagementGroupDetails(int? version = null, DateTimeOffset? updatedOn = null, string updatedBy = null, ManagementGroupParentCreateOptions parent = null) - { - return new CreateManagementGroupDetails(version, updatedOn, updatedBy, parent, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The name of the parent management group. - /// The friendly name of the parent management group. - /// A new instance for mocking. - public static ManagementGroupParentCreateOptions ManagementGroupParentCreateOptions(string id = null, string name = null, string displayName = null) - { - return new ManagementGroupParentCreateOptions(id, name, displayName, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The fully qualified resource type which includes provider namespace (e.g. Microsoft.Management/managementGroups). - /// The fully qualified ID for the child resource (management group or subscription). For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The name of the child entity. - /// The friendly name of the child resource. - /// The list of children. - /// A new instance for mocking. - public static ManagementGroupChildOptions ManagementGroupChildOptions(ManagementGroupChildType? childType = null, string id = null, string name = null, string displayName = null, IEnumerable children = null) - { - children ??= new List(); - - return new ManagementGroupChildOptions( - childType, - id, - name, - displayName, - children?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The friendly name of the management group. - /// The ID of the parent management group. - /// A new instance for mocking. - public static DescendantData DescendantData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, string displayName = null, ResourceIdentifier parentId = null) - { - return new DescendantData( - id, - name, - resourceType, - systemData, - displayName, - parentId != null ? new DescendantParentGroupInfo(parentId, serializedAdditionalRawData: null) : null, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The AAD Tenant ID associated with the subscription. For example, 00000000-0000-0000-0000-000000000000. - /// The friendly name of the subscription. - /// The ID of the parent management group. - /// The state of the subscription. - /// A new instance for mocking. - public static ManagementGroupSubscriptionData ManagementGroupSubscriptionData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, string tenant = null, string displayName = null, ResourceIdentifier parentId = null, string state = null) - { - return new ManagementGroupSubscriptionData( - id, - name, - resourceType, - systemData, - tenant, - displayName, - parentId != null ? new DescendantParentGroupInfo(parentId, serializedAdditionalRawData: null) : null, - state, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// Required. True indicates name is valid and available. False indicates the name is invalid, unavailable, or both. - /// Required if nameAvailable == false. Invalid indicates the name provided does not match the resource provider's naming requirements (incorrect length, unsupported characters, etc.) AlreadyExists indicates that the name is already in use and is therefore unavailable. - /// Required if nameAvailable == false. Localized. If reason == invalid, provide the user with the reason why the given name is invalid, and provide the resource naming requirements so that the user can select a valid name. If reason == AlreadyExists, explain that is already in use, and direct them to select a different name. - /// A new instance for mocking. - public static ManagementGroupNameAvailabilityResult ManagementGroupNameAvailabilityResult(bool? nameAvailable = null, ManagementGroupNameUnavailableReason? reason = null, string message = null) - { - return new ManagementGroupNameAvailabilityResult(nameAvailable, reason, message, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The AAD Tenant ID associated with the entity. For example, 00000000-0000-0000-0000-000000000000. - /// The friendly name of the management group. - /// (Optional) The ID of the parent management group. - /// The users specific permissions to this item. - /// The users specific permissions to this item. - /// Number of Descendants. - /// Number of children is the number of Groups and Subscriptions that are exactly one level underneath the current Group. - /// Number of children is the number of Groups that are exactly one level underneath the current Group. - /// The parent display name chain from the root group to the immediate parent. - /// The parent name chain from the root group to the immediate parent. - /// A new instance for mocking. - public static EntityData EntityData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, Guid? tenantId = null, string displayName = null, ResourceIdentifier parentId = null, EntityPermission? permissions = null, EntityPermission? inheritedPermissions = null, int? numberOfDescendants = null, int? numberOfChildren = null, int? numberOfChildGroups = null, IEnumerable parentDisplayNameChain = null, IEnumerable parentNameChain = null) - { - parentDisplayNameChain ??= new List(); - parentNameChain ??= new List(); - - return new EntityData( - id, - name, - resourceType, - systemData, - tenantId, - displayName, - parentId != null ? ResourceManagerModelFactory.SubResource(parentId) : null, - permissions, - inheritedPermissions, - numberOfDescendants, - numberOfChildren, - numberOfChildGroups, - parentDisplayNameChain?.ToList(), - parentNameChain?.ToList(), - serializedAdditionalRawData: null); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/EntitiesRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/EntitiesRestOperations.cs deleted file mode 100644 index e69f3eae1e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/EntitiesRestOperations.cs +++ /dev/null @@ -1,337 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups.Models; - -namespace Azure.ResourceManager.ManagementGroups -{ - internal partial class EntitiesRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of EntitiesRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public EntitiesRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2021-04-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateListRequestUri(string skipToken, int? skip, int? top, string select, EntitySearchOption? search, string filter, EntityViewOption? view, string groupName, string cacheControl) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/getEntities", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (skipToken != null) - { - uri.AppendQuery("$skiptoken", skipToken, true); - } - if (skip != null) - { - uri.AppendQuery("$skip", skip.Value, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - if (select != null) - { - uri.AppendQuery("$select", select, true); - } - if (search != null) - { - uri.AppendQuery("$search", search.Value.ToString(), true); - } - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - if (view != null) - { - uri.AppendQuery("$view", view.Value.ToString(), true); - } - if (groupName != null) - { - uri.AppendQuery("groupName", groupName, true); - } - return uri; - } - - internal HttpMessage CreateListRequest(string skipToken, int? skip, int? top, string select, EntitySearchOption? search, string filter, EntityViewOption? view, string groupName, string cacheControl) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/getEntities", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (skipToken != null) - { - uri.AppendQuery("$skiptoken", skipToken, true); - } - if (skip != null) - { - uri.AppendQuery("$skip", skip.Value, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - if (select != null) - { - uri.AppendQuery("$select", select, true); - } - if (search != null) - { - uri.AppendQuery("$search", search.Value.ToString(), true); - } - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - if (view != null) - { - uri.AppendQuery("$view", view.Value.ToString(), true); - } - if (groupName != null) - { - uri.AppendQuery("groupName", groupName, true); - } - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// List all entities (Management Groups, Subscriptions, etc.) for the authenticated user. - /// - /// - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of entities to skip over when retrieving results. Passing this in will override $skipToken. - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// This parameter specifies the fields to include in the response. Can include any combination of Name,DisplayName,Type,ParentDisplayNameChain,ParentChain, e.g. '$select=Name,DisplayName,Type,ParentDisplayNameChain,ParentNameChain'. When specified the $select parameter can override select in $skipToken. - /// - /// The $search parameter is used in conjunction with the $filter parameter to return three different outputs depending on the parameter passed in. - /// With $search=AllowedParents the API will return the entity info of all groups that the requested entity will be able to reparent to as determined by the user's permissions. - /// With $search=AllowedChildren the API will return the entity info of all entities that can be added as children of the requested entity. - /// With $search=ParentAndFirstLevelChildren the API will return the parent and first level of children that the user has either direct access to or indirect access via one of their descendants. - /// With $search=ParentOnly the API will return only the group if the user has access to at least one of the descendants of the group. - /// With $search=ChildrenOnly the API will return only the first level of children of the group entity info specified in $filter. The user must have direct access to the children entities or one of it's descendants for it to show up in the results. - /// - /// The filter parameter allows you to filter on the the name or display name fields. You can check for equality on the name field (e.g. name eq '{entityName}') and you can check for substrings on either the name or display name fields(e.g. contains(name, '{substringToSearch}'), contains(displayName, '{substringToSearch')). Note that the '{entityName}' and '{substringToSearch}' fields are checked case insensitively. - /// The view parameter allows clients to filter the type of data that is returned by the getEntities call. - /// A filter which allows the get entities call to focus on a particular group (i.e. "$filter=name eq 'groupName'"). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public async Task> ListAsync(string skipToken = null, int? skip = null, int? top = null, string select = null, EntitySearchOption? search = null, string filter = null, EntityViewOption? view = null, string groupName = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(skipToken, skip, top, select, search, filter, view, groupName, cacheControl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - EntityListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = EntityListResult.DeserializeEntityListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// List all entities (Management Groups, Subscriptions, etc.) for the authenticated user. - /// - /// - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of entities to skip over when retrieving results. Passing this in will override $skipToken. - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// This parameter specifies the fields to include in the response. Can include any combination of Name,DisplayName,Type,ParentDisplayNameChain,ParentChain, e.g. '$select=Name,DisplayName,Type,ParentDisplayNameChain,ParentNameChain'. When specified the $select parameter can override select in $skipToken. - /// - /// The $search parameter is used in conjunction with the $filter parameter to return three different outputs depending on the parameter passed in. - /// With $search=AllowedParents the API will return the entity info of all groups that the requested entity will be able to reparent to as determined by the user's permissions. - /// With $search=AllowedChildren the API will return the entity info of all entities that can be added as children of the requested entity. - /// With $search=ParentAndFirstLevelChildren the API will return the parent and first level of children that the user has either direct access to or indirect access via one of their descendants. - /// With $search=ParentOnly the API will return only the group if the user has access to at least one of the descendants of the group. - /// With $search=ChildrenOnly the API will return only the first level of children of the group entity info specified in $filter. The user must have direct access to the children entities or one of it's descendants for it to show up in the results. - /// - /// The filter parameter allows you to filter on the the name or display name fields. You can check for equality on the name field (e.g. name eq '{entityName}') and you can check for substrings on either the name or display name fields(e.g. contains(name, '{substringToSearch}'), contains(displayName, '{substringToSearch')). Note that the '{entityName}' and '{substringToSearch}' fields are checked case insensitively. - /// The view parameter allows clients to filter the type of data that is returned by the getEntities call. - /// A filter which allows the get entities call to focus on a particular group (i.e. "$filter=name eq 'groupName'"). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public Response List(string skipToken = null, int? skip = null, int? top = null, string select = null, EntitySearchOption? search = null, string filter = null, EntityViewOption? view = null, string groupName = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(skipToken, skip, top, select, search, filter, view, groupName, cacheControl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - EntityListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = EntityListResult.DeserializeEntityListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string skipToken, int? skip, int? top, string select, EntitySearchOption? search, string filter, EntityViewOption? view, string groupName, string cacheControl) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string skipToken, int? skip, int? top, string select, EntitySearchOption? search, string filter, EntityViewOption? view, string groupName, string cacheControl) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// List all entities (Management Groups, Subscriptions, etc.) for the authenticated user. - /// - /// - /// The URL to the next page of results. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of entities to skip over when retrieving results. Passing this in will override $skipToken. - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// This parameter specifies the fields to include in the response. Can include any combination of Name,DisplayName,Type,ParentDisplayNameChain,ParentChain, e.g. '$select=Name,DisplayName,Type,ParentDisplayNameChain,ParentNameChain'. When specified the $select parameter can override select in $skipToken. - /// - /// The $search parameter is used in conjunction with the $filter parameter to return three different outputs depending on the parameter passed in. - /// With $search=AllowedParents the API will return the entity info of all groups that the requested entity will be able to reparent to as determined by the user's permissions. - /// With $search=AllowedChildren the API will return the entity info of all entities that can be added as children of the requested entity. - /// With $search=ParentAndFirstLevelChildren the API will return the parent and first level of children that the user has either direct access to or indirect access via one of their descendants. - /// With $search=ParentOnly the API will return only the group if the user has access to at least one of the descendants of the group. - /// With $search=ChildrenOnly the API will return only the first level of children of the group entity info specified in $filter. The user must have direct access to the children entities or one of it's descendants for it to show up in the results. - /// - /// The filter parameter allows you to filter on the the name or display name fields. You can check for equality on the name field (e.g. name eq '{entityName}') and you can check for substrings on either the name or display name fields(e.g. contains(name, '{substringToSearch}'), contains(displayName, '{substringToSearch')). Note that the '{entityName}' and '{substringToSearch}' fields are checked case insensitively. - /// The view parameter allows clients to filter the type of data that is returned by the getEntities call. - /// A filter which allows the get entities call to focus on a particular group (i.e. "$filter=name eq 'groupName'"). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - public async Task> ListNextPageAsync(string nextLink, string skipToken = null, int? skip = null, int? top = null, string select = null, EntitySearchOption? search = null, string filter = null, EntityViewOption? view = null, string groupName = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink, skipToken, skip, top, select, search, filter, view, groupName, cacheControl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - EntityListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = EntityListResult.DeserializeEntityListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// List all entities (Management Groups, Subscriptions, etc.) for the authenticated user. - /// - /// - /// The URL to the next page of results. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of entities to skip over when retrieving results. Passing this in will override $skipToken. - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// This parameter specifies the fields to include in the response. Can include any combination of Name,DisplayName,Type,ParentDisplayNameChain,ParentChain, e.g. '$select=Name,DisplayName,Type,ParentDisplayNameChain,ParentNameChain'. When specified the $select parameter can override select in $skipToken. - /// - /// The $search parameter is used in conjunction with the $filter parameter to return three different outputs depending on the parameter passed in. - /// With $search=AllowedParents the API will return the entity info of all groups that the requested entity will be able to reparent to as determined by the user's permissions. - /// With $search=AllowedChildren the API will return the entity info of all entities that can be added as children of the requested entity. - /// With $search=ParentAndFirstLevelChildren the API will return the parent and first level of children that the user has either direct access to or indirect access via one of their descendants. - /// With $search=ParentOnly the API will return only the group if the user has access to at least one of the descendants of the group. - /// With $search=ChildrenOnly the API will return only the first level of children of the group entity info specified in $filter. The user must have direct access to the children entities or one of it's descendants for it to show up in the results. - /// - /// The filter parameter allows you to filter on the the name or display name fields. You can check for equality on the name field (e.g. name eq '{entityName}') and you can check for substrings on either the name or display name fields(e.g. contains(name, '{substringToSearch}'), contains(displayName, '{substringToSearch')). Note that the '{entityName}' and '{substringToSearch}' fields are checked case insensitively. - /// The view parameter allows clients to filter the type of data that is returned by the getEntities call. - /// A filter which allows the get entities call to focus on a particular group (i.e. "$filter=name eq 'groupName'"). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - public Response ListNextPage(string nextLink, string skipToken = null, int? skip = null, int? top = null, string select = null, EntitySearchOption? search = null, string filter = null, EntityViewOption? view = null, string groupName = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink, skipToken, skip, top, select, search, filter, view, groupName, cacheControl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - EntityListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = EntityListResult.DeserializeEntityListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/ManagementGroupSubscriptionsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/ManagementGroupSubscriptionsRestOperations.cs deleted file mode 100644 index 5a9ce3d7e5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/ManagementGroupSubscriptionsRestOperations.cs +++ /dev/null @@ -1,517 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups.Models; - -namespace Azure.ResourceManager.ManagementGroups -{ - internal partial class ManagementGroupSubscriptionsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of ManagementGroupSubscriptionsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public ManagementGroupSubscriptionsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2021-04-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateCreateRequestUri(string groupId, string subscriptionId, string cacheControl) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateRequest(string groupId, string subscriptionId, string cacheControl) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// Associates existing subscription with the management group. - /// - /// - /// Management Group ID. - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> CreateAsync(string groupId, string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateCreateRequest(groupId, subscriptionId, cacheControl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupSubscriptionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementGroupSubscriptionData.DeserializeManagementGroupSubscriptionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// Associates existing subscription with the management group. - /// - /// - /// Management Group ID. - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Create(string groupId, string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateCreateRequest(groupId, subscriptionId, cacheControl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupSubscriptionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementGroupSubscriptionData.DeserializeManagementGroupSubscriptionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteRequestUri(string groupId, string subscriptionId, string cacheControl) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteRequest(string groupId, string subscriptionId, string cacheControl) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// De-associates subscription from the management group. - /// - /// - /// Management Group ID. - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task DeleteAsync(string groupId, string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateDeleteRequest(groupId, subscriptionId, cacheControl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// De-associates subscription from the management group. - /// - /// - /// Management Group ID. - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Delete(string groupId, string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateDeleteRequest(groupId, subscriptionId, cacheControl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetSubscriptionRequestUri(string groupId, string subscriptionId, string cacheControl) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetSubscriptionRequest(string groupId, string subscriptionId, string cacheControl) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// Retrieves details about given subscription which is associated with the management group. - /// - /// - /// Management Group ID. - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> GetSubscriptionAsync(string groupId, string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateGetSubscriptionRequest(groupId, subscriptionId, cacheControl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupSubscriptionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementGroupSubscriptionData.DeserializeManagementGroupSubscriptionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ManagementGroupSubscriptionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// Retrieves details about given subscription which is associated with the management group. - /// - /// - /// Management Group ID. - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response GetSubscription(string groupId, string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateGetSubscriptionRequest(groupId, subscriptionId, cacheControl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupSubscriptionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementGroupSubscriptionData.DeserializeManagementGroupSubscriptionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ManagementGroupSubscriptionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetSubscriptionsUnderManagementGroupRequestUri(string groupId, string skipToken) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/subscriptions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (skipToken != null) - { - uri.AppendQuery("$skiptoken", skipToken, true); - } - return uri; - } - - internal HttpMessage CreateGetSubscriptionsUnderManagementGroupRequest(string groupId, string skipToken) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/subscriptions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (skipToken != null) - { - uri.AppendQuery("$skiptoken", skipToken, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// Retrieves details about all subscriptions which are associated with the management group. - /// - /// - /// Management Group ID. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetSubscriptionsUnderManagementGroupAsync(string groupId, string skipToken = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetSubscriptionsUnderManagementGroupRequest(groupId, skipToken); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ListSubscriptionUnderManagementGroup value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ListSubscriptionUnderManagementGroup.DeserializeListSubscriptionUnderManagementGroup(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// Retrieves details about all subscriptions which are associated with the management group. - /// - /// - /// Management Group ID. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response GetSubscriptionsUnderManagementGroup(string groupId, string skipToken = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetSubscriptionsUnderManagementGroupRequest(groupId, skipToken); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ListSubscriptionUnderManagementGroup value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ListSubscriptionUnderManagementGroup.DeserializeListSubscriptionUnderManagementGroup(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetSubscriptionsUnderManagementGroupNextPageRequestUri(string nextLink, string groupId, string skipToken) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateGetSubscriptionsUnderManagementGroupNextPageRequest(string nextLink, string groupId, string skipToken) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// Retrieves details about all subscriptions which are associated with the management group. - /// - /// - /// The URL to the next page of results. - /// Management Group ID. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetSubscriptionsUnderManagementGroupNextPageAsync(string nextLink, string groupId, string skipToken = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetSubscriptionsUnderManagementGroupNextPageRequest(nextLink, groupId, skipToken); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ListSubscriptionUnderManagementGroup value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ListSubscriptionUnderManagementGroup.DeserializeListSubscriptionUnderManagementGroup(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// Retrieves details about all subscriptions which are associated with the management group. - /// - /// - /// The URL to the next page of results. - /// Management Group ID. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response GetSubscriptionsUnderManagementGroupNextPage(string nextLink, string groupId, string skipToken = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetSubscriptionsUnderManagementGroupNextPageRequest(nextLink, groupId, skipToken); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ListSubscriptionUnderManagementGroup value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ListSubscriptionUnderManagementGroup.DeserializeListSubscriptionUnderManagementGroup(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/ManagementGroupsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/ManagementGroupsRestOperations.cs deleted file mode 100644 index f284696f8b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/ManagementGroupsRestOperations.cs +++ /dev/null @@ -1,897 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups.Models; - -namespace Azure.ResourceManager.ManagementGroups -{ - internal partial class ManagementGroupsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of ManagementGroupsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public ManagementGroupsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2021-04-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateListRequestUri(string cacheControl, string skipToken) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (skipToken != null) - { - uri.AppendQuery("$skiptoken", skipToken, true); - } - return uri; - } - - internal HttpMessage CreateListRequest(string cacheControl, string skipToken) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (skipToken != null) - { - uri.AppendQuery("$skiptoken", skipToken, true); - } - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// List management groups for the authenticated user. - /// - /// - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - public async Task> ListAsync(string cacheControl = null, string skipToken = null, CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(cacheControl, skipToken); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementGroupListResult.DeserializeManagementGroupListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// List management groups for the authenticated user. - /// - /// - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - public Response List(string cacheControl = null, string skipToken = null, CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(cacheControl, skipToken); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementGroupListResult.DeserializeManagementGroupListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetRequestUri(string groupId, ManagementGroupExpandType? expand, bool? recurse, string filter, string cacheControl) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendQuery("api-version", _apiVersion, true); - if (expand != null) - { - uri.AppendQuery("$expand", expand.Value.ToString(), true); - } - if (recurse != null) - { - uri.AppendQuery("$recurse", recurse.Value, true); - } - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - return uri; - } - - internal HttpMessage CreateGetRequest(string groupId, ManagementGroupExpandType? expand, bool? recurse, string filter, string cacheControl) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendQuery("api-version", _apiVersion, true); - if (expand != null) - { - uri.AppendQuery("$expand", expand.Value.ToString(), true); - } - if (recurse != null) - { - uri.AppendQuery("$recurse", recurse.Value, true); - } - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// Get the details of the management group. - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetAsync(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetRequest(groupId, expand, recurse, filter, cacheControl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementGroupData.DeserializeManagementGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ManagementGroupData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// Get the details of the management group. - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response Get(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetRequest(groupId, expand, recurse, filter, cacheControl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementGroupData.DeserializeManagementGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ManagementGroupData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateCreateOrUpdateRequestUri(string groupId, ManagementGroupCreateOrUpdateContent content, string cacheControl) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateRequest(string groupId, ManagementGroupCreateOrUpdateContent content, string cacheControl) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content0 = new Utf8JsonRequestContent(); - content0.JsonWriter.WriteObjectValue(content, ModelSerializationExtensions.WireOptions); - request.Content = content0; - _userAgent.Apply(message); - return message; - } - - /// - /// Create or update a management group. - /// If a management group is already created and a subsequent create request is issued with different properties, the management group properties will be updated. - /// - /// - /// Management Group ID. - /// Management group creation parameters. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task CreateOrUpdateAsync(string groupId, ManagementGroupCreateOrUpdateContent content, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNull(content, nameof(content)); - - using var message = CreateCreateOrUpdateRequest(groupId, content, cacheControl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// Create or update a management group. - /// If a management group is already created and a subsequent create request is issued with different properties, the management group properties will be updated. - /// - /// - /// Management Group ID. - /// Management group creation parameters. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response CreateOrUpdate(string groupId, ManagementGroupCreateOrUpdateContent content, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNull(content, nameof(content)); - - using var message = CreateCreateOrUpdateRequest(groupId, content, cacheControl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateUpdateRequestUri(string groupId, ManagementGroupPatch patch, string cacheControl) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateUpdateRequest(string groupId, ManagementGroupPatch patch, string cacheControl) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Patch; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(patch, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// - /// Update a management group. - /// - /// - /// Management Group ID. - /// Management group patch parameters. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> UpdateAsync(string groupId, ManagementGroupPatch patch, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNull(patch, nameof(patch)); - - using var message = CreateUpdateRequest(groupId, patch, cacheControl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementGroupData.DeserializeManagementGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// Update a management group. - /// - /// - /// Management Group ID. - /// Management group patch parameters. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response Update(string groupId, ManagementGroupPatch patch, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNull(patch, nameof(patch)); - - using var message = CreateUpdateRequest(groupId, patch, cacheControl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementGroupData.DeserializeManagementGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteRequestUri(string groupId, string cacheControl) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteRequest(string groupId, string cacheControl) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// Delete management group. - /// If a management group contains child resources, the request will fail. - /// - /// - /// Management Group ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task DeleteAsync(string groupId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateDeleteRequest(groupId, cacheControl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 202: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// Delete management group. - /// If a management group contains child resources, the request will fail. - /// - /// - /// Management Group ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response Delete(string groupId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateDeleteRequest(groupId, cacheControl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 202: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetDescendantsRequestUri(string groupId, string skipToken, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/descendants", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (skipToken != null) - { - uri.AppendQuery("$skiptoken", skipToken, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - return uri; - } - - internal HttpMessage CreateGetDescendantsRequest(string groupId, string skipToken, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/descendants", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (skipToken != null) - { - uri.AppendQuery("$skiptoken", skipToken, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// List all entities that descend from a management group. - /// - /// - /// Management Group ID. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetDescendantsAsync(string groupId, string skipToken = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetDescendantsRequest(groupId, skipToken, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - DescendantListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = DescendantListResult.DeserializeDescendantListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// List all entities that descend from a management group. - /// - /// - /// Management Group ID. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response GetDescendants(string groupId, string skipToken = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetDescendantsRequest(groupId, skipToken, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - DescendantListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = DescendantListResult.DeserializeDescendantListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateCheckNameAvailabilityRequestUri(ManagementGroupNameAvailabilityContent content) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/checkNameAvailability", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCheckNameAvailabilityRequest(ManagementGroupNameAvailabilityContent content) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/checkNameAvailability", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content0 = new Utf8JsonRequestContent(); - content0.JsonWriter.WriteObjectValue(content, ModelSerializationExtensions.WireOptions); - request.Content = content0; - _userAgent.Apply(message); - return message; - } - - /// Checks if the specified management group name is valid and unique. - /// Management group name availability check parameters. - /// The cancellation token to use. - /// is null. - public async Task> CheckNameAvailabilityAsync(ManagementGroupNameAvailabilityContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(content, nameof(content)); - - using var message = CreateCheckNameAvailabilityRequest(content); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupNameAvailabilityResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementGroupNameAvailabilityResult.DeserializeManagementGroupNameAvailabilityResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Checks if the specified management group name is valid and unique. - /// Management group name availability check parameters. - /// The cancellation token to use. - /// is null. - public Response CheckNameAvailability(ManagementGroupNameAvailabilityContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(content, nameof(content)); - - using var message = CreateCheckNameAvailabilityRequest(content); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupNameAvailabilityResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementGroupNameAvailabilityResult.DeserializeManagementGroupNameAvailabilityResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string cacheControl, string skipToken) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string cacheControl, string skipToken) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// List management groups for the authenticated user. - /// - /// - /// The URL to the next page of results. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// is null. - public async Task> ListNextPageAsync(string nextLink, string cacheControl = null, string skipToken = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink, cacheControl, skipToken); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementGroupListResult.DeserializeManagementGroupListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// List management groups for the authenticated user. - /// - /// - /// The URL to the next page of results. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// is null. - public Response ListNextPage(string nextLink, string cacheControl = null, string skipToken = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink, cacheControl, skipToken); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementGroupListResult.DeserializeManagementGroupListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetDescendantsNextPageRequestUri(string nextLink, string groupId, string skipToken, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateGetDescendantsNextPageRequest(string nextLink, string groupId, string skipToken, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// List all entities that descend from a management group. - /// - /// - /// The URL to the next page of results. - /// Management Group ID. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetDescendantsNextPageAsync(string nextLink, string groupId, string skipToken = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetDescendantsNextPageRequest(nextLink, groupId, skipToken, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - DescendantListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = DescendantListResult.DeserializeDescendantListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// List all entities that descend from a management group. - /// - /// - /// The URL to the next page of results. - /// Management Group ID. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response GetDescendantsNextPage(string nextLink, string groupId, string skipToken = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetDescendantsNextPageRequest(nextLink, groupId, skipToken, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - DescendantListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = DescendantListResult.DeserializeDescendantListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Properties/AssemblyInfo.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Properties/AssemblyInfo.cs deleted file mode 100644 index 3a31e4dd1d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.Runtime.CompilerServices; -using Azure.Core; - -[assembly: AzureResourceProviderNamespace("Microsoft.Resources")] - -[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] -[assembly: InternalsVisibleTo("Azure.ResourceManager.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] -[assembly: InternalsVisibleTo("Azure.ResourceManager.Perf, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ProviderConstants.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ProviderConstants.cs deleted file mode 100644 index dbce6211e2..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ProviderConstants.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager -{ - internal static class ProviderConstants - { - public static string DefaultProviderNamespace { get; } = ClientDiagnostics.GetResourceProviderNamespace(typeof(ProviderConstants).Assembly); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/RehydrationOperation.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/RehydrationOperation.cs deleted file mode 100644 index 7fe620e46e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/RehydrationOperation.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; -using Azure.Core; - -namespace Azure.ResourceManager -{ - internal class RehydrationOperation : ArmOperation - { - private readonly NextLinkOperationImplementation _nextLinkOperation; - private readonly OperationInternal _operation; - - public RehydrationOperation(NextLinkOperationImplementation nextLinkOperation, OperationState operationState, ClientOptions? options = null) - { - _nextLinkOperation = nextLinkOperation; - _operation = operationState.HasCompleted - ? new OperationInternal(operationState) - : new OperationInternal(nextLinkOperation, new ClientDiagnostics(options ?? ClientOptions.Default), operationState.RawResponse); - } - - public override string Id => _nextLinkOperation.OperationId; - - public override RehydrationToken? GetRehydrationToken() => _nextLinkOperation?.GetRehydrationToken(); - - public override bool HasCompleted => _operation.HasCompleted; - - public override Response GetRawResponse() => _operation.RawResponse; - - public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); - - public override ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/RehydrationOperationOfT.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/RehydrationOperationOfT.cs deleted file mode 100644 index 21b1298880..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/RehydrationOperationOfT.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager -{ -#pragma warning disable SA1649 // File name should match first type name - internal class RehydrationOperation : ArmOperation where T : notnull -#pragma warning restore SA1649 // File name should match first type name - { - private readonly OperationInternal _operation; - private readonly NextLinkOperationImplementation _nextLinkOperation; - - public RehydrationOperation(NextLinkOperationImplementation nextLinkOperation, OperationState operationState, IOperation operation, ClientOptions? options = null) - { - _nextLinkOperation = nextLinkOperation; - _operation = operationState.HasCompleted - ? new OperationInternal(operationState) - : new OperationInternal(operation, new ClientDiagnostics(options ?? ClientOptions.Default), operationState.RawResponse); - } - - public override T Value => _operation.Value; - - public override bool HasValue => _operation.HasValue; - - public override string Id => _nextLinkOperation.OperationId; - - public override bool HasCompleted => _operation.HasCompleted; - - public override Response GetRawResponse() => _operation.RawResponse; - - public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); - - public override ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ResourceManagerExtensions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ResourceManagerExtensions.cs deleted file mode 100644 index 19a2d39743..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ResourceManagerExtensions.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using Azure.Core; -using Azure.ResourceManager.Resources; -using System; - -namespace Azure.ResourceManager -{ - /// - /// Extension class for resource manager. - /// - internal static class ResourceManagerExtensions - { - /// - /// Gets the correlation id from x-ms-correlation-id. - /// - public static string GetCorrelationId(this Response response) - { - string correlationId = null; - response.Headers.TryGetValue("x-ms-correlation-request-id", out correlationId); - return correlationId; - } - - internal static ResourceIdentifier GetSubscriptionResourceIdentifier(this ResourceIdentifier id) - { - if (id.ResourceType == SubscriptionResource.ResourceType) - return id; - - ResourceIdentifier parent = id.Parent; - while (parent != null && parent.ResourceType != SubscriptionResource.ResourceType) - { - parent = parent.Parent; - } - - return parent?.ResourceType == SubscriptionResource.ResourceType ? parent : null; - } - - internal static string GetManifestName(this AzureStackProfile profile) - { - var namePrefix = "Azure.ResourceManager.Assets.Profile."; - var nameSuffix = profile switch - { - AzureStackProfile.Profile20200901Hybrid => "2020-09-01-hybrid.json", - _ => throw new ArgumentOutOfRangeException(nameof(profile), profile, null) - }; - return namePrefix + nameSuffix; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/ResourceManagerJsonContext.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/ResourceManagerJsonContext.cs deleted file mode 100644 index c252053234..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/ResourceManagerJsonContext.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.Collections.Generic; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Text.Json.Serialization.Metadata; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager -{ - [JsonSourceGenerationOptions(Converters = [typeof(ResponseErrorConverter)])] - [JsonSerializable(typeof(ManagedServiceIdentityType))] - [JsonSerializable(typeof(UserAssignedIdentity))] - [JsonSerializable(typeof(SystemData))] - [JsonSerializable(typeof(OperationStatusResult))] - [JsonSerializable(typeof(ManagedServiceIdentity))] - [JsonSerializable(typeof(ArmPlan))] - [JsonSerializable(typeof(SubResource))] - [JsonSerializable(typeof(ExtendedLocation))] - [JsonSerializable(typeof(ArmEnvironment))] - [JsonSerializable(typeof(JsonElement))] - [JsonSerializable(typeof(Dictionary>))] - [JsonSerializable(typeof(Dictionary))] - internal partial class ResourceManagerJsonContext : JsonSerializerContext - { - private static JsonTypeInfo _responseError; - - /// - /// Gets the for . - /// Manually defined because the built-in on - /// is internal and inaccessible to the System.Text.Json source generator. - /// - public JsonTypeInfo ResponseError => _responseError ??= JsonMetadataServices.CreateValueInfo(Options, new ResponseErrorConverter()); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ArmClient.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ArmClient.cs deleted file mode 100644 index e26f631cc1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ArmClient.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using Azure.Core; -using Azure.ResourceManager.Resources; - -namespace Azure.ResourceManager -{ - /// - /// The entry point for all ARM clients. - /// - [CodeGenSuppress("GetTenantResource", typeof(ResourceIdentifier))] - public partial class ArmClient - { - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual GenericResource GetGenericResource(ResourceIdentifier id) - { - GenericResource.ValidateResourceId(id); - return new GenericResource(this, id); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ArmRestApiCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ArmRestApiCollection.cs deleted file mode 100644 index 25e587549e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ArmRestApiCollection.cs +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class which represents the RestApis for a given azure namespace. - /// - public partial class ArmRestApiCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _clientDiagnostics; - private readonly string _nameSpace; - private readonly ResourceProviderCollection _providerCollection; - - /// Represents the REST operations. - private RestOperations _restClient; - - /// Initializes a new instance of the class for mocking. - protected ArmRestApiCollection() - { - } - - /// Initializes a new instance of RestApiCollection class. - /// The resource representing the parent resource. - /// The namespace for the rest apis. - internal ArmRestApiCollection(ArmResource operation, string nameSpace) - : base(operation.Client, operation.Id) - { - _clientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", nameSpace, Diagnostics); - _nameSpace = nameSpace; - _providerCollection = new ResourceProviderCollection(Client.GetSubscriptionResource(Id)); - } - - private RestOperations GetRestClient(CancellationToken cancellationToken = default) - { - return _restClient ??= new RestOperations( - _nameSpace, - _providerCollection.GetApiVersion(new ResourceType($"{_nameSpace}/operations"), cancellationToken), - _clientDiagnostics, - Pipeline, - Diagnostics.ApplicationId, - Endpoint); - } - - private async Task GetRestClientAsync(CancellationToken cancellationToken = default) - { - return _restClient ??= new RestOperations( - _nameSpace, - await _providerCollection.GetApiVersionAsync(new ResourceType($"{_nameSpace}/operations"), cancellationToken).ConfigureAwait(false), - _clientDiagnostics, - Pipeline, - Diagnostics.ApplicationId, - Endpoint); - } - - /// Gets a list of operations. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(CancellationToken cancellationToken = default) - { - Page FirstPageFunc(int? pageSizeHint) - { - using var scope = _clientDiagnostics.CreateScope("ArmRestApiCollection.GetAll"); - scope.Start(); - try - { - var response = GetRestClient().List(cancellationToken: cancellationToken); - return Page.FromValues(response.Value.Value, null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - return PageableHelpers.CreateEnumerable(FirstPageFunc, null); - } - - /// Gets a list of operations. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(CancellationToken cancellationToken = default) - { - async Task> FirstPageFunc(int? pageSizeHint) - { - using var scope = _clientDiagnostics.CreateScope("ArmRestApiCollection.GetAll"); - scope.Start(); - try - { - var restClient = await GetRestClientAsync().ConfigureAwait(false); - var response = await restClient.ListAsync(cancellationToken: cancellationToken).ConfigureAwait(false); - return Page.FromValues(response.Value.Value, null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, null); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Extensions/ArmResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Extensions/ArmResource.cs deleted file mode 100644 index 451ced6807..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Extensions/ArmResource.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using Azure.Core; -using Azure.ResourceManager.Resources; - -namespace Azure.ResourceManager -{ - public partial class ArmResource - { - /// Gets an object representing a TagResource along with the instance operations that can be performed on it in the ArmResource. - /// Returns a object. - public virtual TagResource GetTagResource() - { - return GetCachedClient(client => new TagResource(client, new ResourceIdentifier(Id.ToString() + "/providers/Microsoft.Resources/tags/default"))); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/FeatureResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/FeatureResource.cs deleted file mode 100644 index ebfa136947..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/FeatureResource.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using Azure.Core; - -[assembly:CodeGenSuppressType("ErrorDefinition")] -[assembly:CodeGenSuppressType("FeatureErrorResponse")] -namespace Azure.ResourceManager.Resources -{ - /// A Class representing a Feature along with the instance operations that can be performed on it. - public partial class FeatureResource : ArmResource - { - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType.GetLastType() != "features") - { - throw new InvalidOperationException($"Invalid resourcetype found when intializing FeatureOperations: {id.ResourceType}"); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/GenericResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/GenericResource.cs deleted file mode 100644 index 7de2f6b25d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/GenericResource.cs +++ /dev/null @@ -1,433 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -[assembly: CodeGenSuppressType("GenericResourceFilter")] -[assembly: CodeGenSuppressType("GenericResource")] -[assembly: CodeGenSuppressType("GenericResourceIdentityType")] -namespace Azure.ResourceManager.Resources -{ - /// A Class representing a GenericResource along with the instance operations that can be performed on it. - public partial class GenericResource : ArmResource - { - private readonly ClientDiagnostics _clientDiagnostics; - private readonly ResourcesRestOperations _resourcesRestClient; - private readonly GenericResourceData _data; - private readonly ResourceProviderCollection _providerCollection; - - /// Initializes a new instance of the class for mocking. - protected GenericResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal GenericResource(ArmClient client, GenericResourceData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal GenericResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - ResourceIdentifier subscription = Id.GetSubscriptionResourceIdentifier(); - if (subscription == null) - { - throw new ArgumentException("Only resource in a subscription is supported"); - } - _clientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", Id.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(Id.ResourceType, out string apiVersion); - _resourcesRestClient = new ResourcesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, apiVersion); - _providerCollection = new ResourceProviderCollection(Client.GetSubscriptionResource(subscription)); - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual GenericResourceData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - -#pragma warning disable CA1801 // Review unused parameters - internal static void ValidateResourceId(ResourceIdentifier id) -#pragma warning restore CA1801 // Review unused parameters - { - //no op but here for code generation - } - - /// RequestPath: /{resourceId} - /// ContextualPath: /{resourceId} - /// OperationId: Resources_GetById - /// Gets a resource by ID. - /// The cancellation token to use. - public async virtual Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _clientDiagnostics.CreateScope("GenericResource.Get"); - scope.Start(); - try - { - var apiVersion = await GetApiVersionAsync(cancellationToken).ConfigureAwait(false); - var response = await _resourcesRestClient.GetByIdAsync(Id, apiVersion, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new GenericResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// RequestPath: /{resourceId} - /// ContextualPath: /{resourceId} - /// OperationId: Resources_GetById - /// Gets a resource by ID. - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _clientDiagnostics.CreateScope("GenericResource.Get"); - scope.Start(); - try - { - var apiVersion = GetApiVersion(cancellationToken); - var response = _resourcesRestClient.GetById(Id, apiVersion, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new GenericResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// RequestPath: /{resourceId} - /// ContextualPath: /{resourceId} - /// OperationId: Resources_DeleteById - /// Deletes a resource by ID. - /// "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public async virtual Task DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _clientDiagnostics.CreateScope("GenericResource.Delete"); - scope.Start(); - try - { - var apiVersion = await GetApiVersionAsync(cancellationToken).ConfigureAwait(false); - var response = await _resourcesRestClient.DeleteByIdAsync(Id, apiVersion, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(_clientDiagnostics, Pipeline, _resourcesRestClient.CreateDeleteByIdRequest(Id, apiVersion).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// RequestPath: /{resourceId} - /// ContextualPath: /{resourceId} - /// OperationId: Resources_DeleteById - /// Deletes a resource by ID. - /// "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _clientDiagnostics.CreateScope("GenericResource.Delete"); - scope.Start(); - try - { - var apiVersion = GetApiVersion(cancellationToken); - var response = _resourcesRestClient.DeleteById(Id, apiVersion, cancellationToken); - var operation = new ResourcesArmOperation(_clientDiagnostics, Pipeline, _resourcesRestClient.CreateDeleteByIdRequest(Id, apiVersion).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Add a tag to the current resource. - /// The key for the tag. - /// The value for the tag. - /// A token to allow the caller to cancel the call to the service. The default value is . - /// The updated resource with the tag added. - public async virtual Task> AddTagAsync(string key, string value, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(key)) - { - throw new ArgumentNullException(nameof(key), $"{nameof(key)} provided cannot be null or a whitespace."); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResource.AddTag"); - scope.Start(); - try - { - var apiVersion = await GetApiVersionAsync(cancellationToken).ConfigureAwait(false); - var tagPatch = new TagResourcePatch(TagPatchMode.Merge, new Tag(new Dictionary { { key, value } }, null), null); - await GetTagResource().UpdateAsync(WaitUntil.Completed, tagPatch, cancellationToken).ConfigureAwait(false); - var originalResponse = await _resourcesRestClient.GetByIdAsync(Id, apiVersion, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new GenericResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Add a tag to the current resource. - /// The key for the tag. - /// The value for the tag. - /// A token to allow the caller to cancel the call to the service. The default value is . - /// The updated resource with the tag added. - public virtual Response AddTag(string key, string value, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(key)) - { - throw new ArgumentNullException(nameof(key), $"{nameof(key)} provided cannot be null or a whitespace."); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResource.AddTag"); - scope.Start(); - try - { - var apiVersion = GetApiVersion(cancellationToken); - var tagPatch = new TagResourcePatch(TagPatchMode.Merge, new Tag(new Dictionary { { key, value } }, null), null); - GetTagResource().Update(WaitUntil.Completed, tagPatch, cancellationToken: cancellationToken); - var originalResponse = _resourcesRestClient.GetById(Id, apiVersion, cancellationToken); - return Response.FromValue(new GenericResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Replace the tags on the resource with the given set. - /// The set of tags to use as replacement. - /// A token to allow the caller to cancel the call to the service. The default value is . - /// The updated resource with the tags replaced. - public async virtual Task> SetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) - { - if (tags == null) - { - throw new ArgumentNullException(nameof(tags), $"{nameof(tags)} provided cannot be null."); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResource.SetTags"); - scope.Start(); - try - { - var apiVersion = await GetApiVersionAsync(cancellationToken).ConfigureAwait(false); - await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, new TagResourceData(new Tag(tags, null)), cancellationToken: cancellationToken).ConfigureAwait(false); - var originalResponse = await _resourcesRestClient.GetByIdAsync(Id, apiVersion, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new GenericResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Replace the tags on the resource with the given set. - /// The set of tags to use as replacement. - /// A token to allow the caller to cancel the call to the service. The default value is . - /// The updated resource with the tags replaced. - public virtual Response SetTags(IDictionary tags, CancellationToken cancellationToken = default) - { - if (tags == null) - { - throw new ArgumentNullException(nameof(tags), $"{nameof(tags)} provided cannot be null."); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResource.SetTags"); - scope.Start(); - try - { - var apiVersion = GetApiVersion(cancellationToken); - GetTagResource().CreateOrUpdate(WaitUntil.Completed, new TagResourceData(new Tag(tags, null)), cancellationToken: cancellationToken); - var originalResponse = _resourcesRestClient.GetById(Id, apiVersion, cancellationToken); - return Response.FromValue(new GenericResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Removes a tag by key from the resource. - /// The key of the tag to remove. - /// A token to allow the caller to cancel the call to the service. The default value is . - /// The updated resource with the tag removed. - public async virtual Task> RemoveTagAsync(string key, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(key)) - { - throw new ArgumentNullException(nameof(key), $"{nameof(key)} provided cannot be null or a whitespace."); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResource.RemoveTag"); - scope.Start(); - try - { - var apiVersion = await GetApiVersionAsync(cancellationToken).ConfigureAwait(false); - var tagPatch = new TagResourcePatch(TagPatchMode.Delete, new Tag(new Dictionary { { key, string.Empty } }, null), null); - await GetTagResource().UpdateAsync(WaitUntil.Completed, tagPatch, cancellationToken: cancellationToken).ConfigureAwait(false); - var originalResponse = await _resourcesRestClient.GetByIdAsync(Id, apiVersion, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new GenericResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Removes a tag by key from the resource. - /// The key of the tag to remove. - /// A token to allow the caller to cancel the call to the service. The default value is . - /// The updated resource with the tag removed. - public virtual Response RemoveTag(string key, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(key)) - { - throw new ArgumentNullException(nameof(key), $"{nameof(key)} provided cannot be null or a whitespace."); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResource.RemoveTag"); - scope.Start(); - try - { - var apiVersion = GetApiVersion(cancellationToken); - var tagPatch = new TagResourcePatch(TagPatchMode.Delete, new Tag(new Dictionary { { key, string.Empty } }, null), null); - GetTagResource().Update(WaitUntil.Completed, tagPatch, cancellationToken: cancellationToken); - var originalResponse = _resourcesRestClient.GetById(Id, apiVersion, cancellationToken); - return Response.FromValue(new GenericResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// RequestPath: /{resourceId} - /// ContextualPath: /{resourceId} - /// OperationId: Resources_UpdateById - /// Updates a resource by ID. - /// "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Update resource parameters. - /// The cancellation token to use. - /// is null. - public async virtual Task> UpdateAsync(WaitUntil waitUntil, GenericResourceData data, CancellationToken cancellationToken = default) - { - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResource.Update"); - scope.Start(); - try - { - var apiVersion = await GetApiVersionAsync(cancellationToken).ConfigureAwait(false); - var response = await _resourcesRestClient.UpdateByIdAsync(Id, apiVersion, data, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(new GenericResourceOperationSource(Client), _clientDiagnostics, Pipeline, _resourcesRestClient.CreateUpdateByIdRequest(Id, apiVersion, data).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// RequestPath: /{resourceId} - /// ContextualPath: /{resourceId} - /// OperationId: Resources_UpdateById - /// Updates a resource by ID. - /// "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Update resource parameters. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation Update(WaitUntil waitUntil, GenericResourceData data, CancellationToken cancellationToken = default) - { - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResource.Update"); - scope.Start(); - try - { - var apiVersion = GetApiVersion(cancellationToken); - var response = _resourcesRestClient.UpdateById(Id, apiVersion, data, cancellationToken); - var operation = new ResourcesArmOperation(new GenericResourceOperationSource(Client), _clientDiagnostics, Pipeline, _resourcesRestClient.CreateUpdateByIdRequest(Id, apiVersion, data).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - private string GetApiVersion(CancellationToken cancellationToken) - { - string version = _providerCollection.GetApiVersion(Id.ResourceType, cancellationToken); - if (version is null) - { - throw new InvalidOperationException($"An invalid resource id was given {Id}"); - } - return version; - } - - private async Task GetApiVersionAsync(CancellationToken cancellationToken) - { - string version = await _providerCollection.GetApiVersionAsync(Id.ResourceType, cancellationToken).ConfigureAwait(false); - if (version is null) - { - throw new InvalidOperationException($"An invalid resource id was given {Id}"); - } - return version; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/GenericResourceCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/GenericResourceCollection.cs deleted file mode 100644 index ee0a0f75a1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/GenericResourceCollection.cs +++ /dev/null @@ -1,266 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -[assembly: CodeGenSuppressType("GenericResourceCollection")] -namespace Azure.ResourceManager.Resources -{ - /// A class representing collection of GenericResource and their operations over its parent. - public partial class GenericResourceCollection : ArmCollection - { - private readonly ClientDiagnostics _clientDiagnostics; - private readonly ResourcesRestOperations _resourcesRestClient; - - /// Initializes a new instance of the class for mocking. - protected GenericResourceCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal GenericResourceCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _clientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ProviderConstants.DefaultProviderNamespace, Diagnostics); - _resourcesRestClient = new ResourcesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint); - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != TenantResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, TenantResource.ResourceType), nameof(id)); - } - - // Collection level operations. - - /// RequestPath: /{resourceId} - /// ContextualPath: / - /// OperationId: Resources_CreateOrUpdateById - /// Create a resource by ID. - /// "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// Create or update resource parameters. - /// The cancellation token to use. - /// or is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, ResourceIdentifier resourceId, GenericResourceData data, CancellationToken cancellationToken = default) - { - if (resourceId == null) - { - throw new ArgumentNullException(nameof(resourceId)); - } - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResourceCollection.CreateOrUpdate"); - scope.Start(); - try - { - var apiVersion = GetApiVersion(new ResourceIdentifier(resourceId), cancellationToken); - var response = _resourcesRestClient.CreateOrUpdateById(resourceId, apiVersion, data, cancellationToken); - var operation = new ResourcesArmOperation(new GenericResourceOperationSource(Client), _clientDiagnostics, Pipeline, _resourcesRestClient.CreateCreateOrUpdateByIdRequest(resourceId, apiVersion, data).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// RequestPath: /{resourceId} - /// ContextualPath: / - /// OperationId: Resources_CreateOrUpdateById - /// Create a resource by ID. - /// "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// Create or update resource parameters. - /// The cancellation token to use. - /// , or is null. - public async virtual Task> CreateOrUpdateAsync(WaitUntil waitUntil, ResourceIdentifier resourceId, GenericResourceData data, CancellationToken cancellationToken = default) - { - if (resourceId == null) - { - throw new ArgumentNullException(nameof(resourceId)); - } - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResourceCollection.CreateOrUpdate"); - scope.Start(); - try - { - var apiVersion = await GetApiVersionAsync(new ResourceIdentifier(resourceId), cancellationToken).ConfigureAwait(false); - var response = await _resourcesRestClient.CreateOrUpdateByIdAsync(resourceId, apiVersion, data, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(new GenericResourceOperationSource(Client), _clientDiagnostics, Pipeline, _resourcesRestClient.CreateCreateOrUpdateByIdRequest(resourceId, apiVersion, data).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// RequestPath: /{resourceId} - /// ContextualPath: / - /// OperationId: Resources_GetById - /// Gets a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The cancellation token to use. - /// is null. - public virtual Response Get(ResourceIdentifier resourceId, CancellationToken cancellationToken = default) - { - if (resourceId == null) - { - throw new ArgumentNullException(nameof(resourceId)); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResourceCollection.Get"); - scope.Start(); - try - { - var apiVersion = GetApiVersion(new ResourceIdentifier(resourceId), cancellationToken); - var response = _resourcesRestClient.GetById(resourceId, apiVersion, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new GenericResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// RequestPath: /{resourceId} - /// ContextualPath: / - /// OperationId: Resources_GetById - /// Gets a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The cancellation token to use. - /// is null. - public async virtual Task> GetAsync(ResourceIdentifier resourceId, CancellationToken cancellationToken = default) - { - if (resourceId == null) - { - throw new ArgumentNullException(nameof(resourceId)); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResourceCollection.Get"); - scope.Start(); - try - { - var apiVersion = await GetApiVersionAsync(new ResourceIdentifier(resourceId), cancellationToken).ConfigureAwait(false); - var response = await _resourcesRestClient.GetByIdAsync(resourceId, apiVersion, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new GenericResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Tries to get details for this resource from the service. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The cancellation token to use. - /// is null. - public virtual Response Exists(ResourceIdentifier resourceId, CancellationToken cancellationToken = default) - { - if (resourceId == null) - { - throw new ArgumentNullException(nameof(resourceId)); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResourceCollection.Exists"); - scope.Start(); - try - { - var apiVersion = GetApiVersion(new ResourceIdentifier(resourceId), cancellationToken); - var response = _resourcesRestClient.GetById(resourceId, apiVersion, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Tries to get details for this resource from the service. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The cancellation token to use. - /// is null. - public async virtual Task> ExistsAsync(ResourceIdentifier resourceId, CancellationToken cancellationToken = default) - { - if (resourceId == null) - { - throw new ArgumentNullException(nameof(resourceId)); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResourceCollection.Exists"); - scope.Start(); - try - { - var apiVersion = await GetApiVersionAsync(new ResourceIdentifier(resourceId), cancellationToken).ConfigureAwait(false); - var response = await _resourcesRestClient.GetByIdAsync(resourceId, apiVersion, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - private string GetApiVersion(ResourceIdentifier resourceId, CancellationToken cancellationToken) - { - ResourceIdentifier subscription = resourceId.GetSubscriptionResourceIdentifier(); - if (subscription == null) - { - throw new ArgumentException("Only resource id in a subscription is supported", nameof(resourceId)); - } - ResourceProviderCollection collection = new ResourceProviderCollection(Client, subscription); - string version = collection.GetApiVersion(resourceId.ResourceType, cancellationToken); - if (version is null) - { - throw new InvalidOperationException($"An invalid resource id was given {resourceId}"); - } - return version; - } - - private async Task GetApiVersionAsync(ResourceIdentifier resourceId, CancellationToken cancellationToken) - { - ResourceIdentifier subscription = resourceId.GetSubscriptionResourceIdentifier(); - if (subscription == null) - { - throw new ArgumentException("Only resource id in a subscription is supported", nameof(resourceId)); - } - ResourceProviderCollection collection = new ResourceProviderCollection(Client, subscription); - string version = await collection.GetApiVersionAsync(resourceId.ResourceType, cancellationToken).ConfigureAwait(false); - if (version is null) - { - throw new InvalidOperationException($"An invalid resource id was given {resourceId}"); - } - return version; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/GenericResourceData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/GenericResourceData.cs deleted file mode 100644 index f2bf593f62..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/GenericResourceData.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - // this piece of customization code is used for fixing the base class here - public partial class GenericResourceData : TrackedResourceExtendedData - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/HelperSuppressions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/HelperSuppressions.cs deleted file mode 100644 index f7cda07595..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/HelperSuppressions.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using Azure.Core; - -[assembly: CodeGenSuppressType("Azure.ResourceManager.Optional")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.ChangeTrackingList")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.RequestContentHelper")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.Argument")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.ChangeTrackingDictionary")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.ModelSerializationExtensions")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.BicepSerializationHelpers")] diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApi.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApi.Serialization.cs deleted file mode 100644 index af88ab9534..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApi.Serialization.cs +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ArmRestApi : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmRestApi)} does not support '{format}' format."); - } - - writer.WriteStartObject(); - if (format != "W" && Optional.IsDefined(Origin)) - { - writer.WritePropertyName("origin"u8); - writer.WriteStringValue(Origin); - } - if (format != "W" && Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - writer.WritePropertyName("display"u8); - writer.WriteStartObject(); - if (format != "W" && Optional.IsDefined(Operation)) - { - writer.WritePropertyName("operation"u8); - writer.WriteStringValue(Operation); - } - if (format != "W" && Optional.IsDefined(Resource)) - { - writer.WritePropertyName("resource"u8); - writer.WriteStringValue(Resource); - } - if (format != "W" && Optional.IsDefined(Description)) - { - writer.WritePropertyName("description"u8); - writer.WriteStringValue(Description); - } - if (format != "W" && Optional.IsDefined(Provider)) - { - writer.WritePropertyName("provider"u8); - writer.WriteStringValue(Provider); - } - writer.WriteEndObject(); - writer.WriteEndObject(); - } - - ArmRestApi IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmRestApi)} does not support '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeArmRestApi(document.RootElement, options); - } - - internal static ArmRestApi DeserializeArmRestApi(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= new ModelReaderWriterOptions("W"); - - string origin = default; - string name = default; - string operation = default; - string resource = default; - string description = default; - string provider = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("origin")) - { - origin = property.Value.GetString(); - continue; - } - if (property.NameEquals("name")) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("display")) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("operation")) - { - operation = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("resource")) - { - resource = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("description")) - { - description = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("provider")) - { - provider = property0.Value.GetString(); - continue; - } - } - continue; - } - } - return new ArmRestApi(origin, name, operation, resource, description, provider); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ArmRestApi)} does not support '{options.Format}' format."); - } - } - - ArmRestApi IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeArmRestApi(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ArmRestApi)} does not support '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApi.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApi.cs deleted file mode 100644 index 164b744651..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApi.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Describes the properties of an Operation value. - public partial class ArmRestApi - { - /// Initializes a new instance of RestApi for mocking. - internal ArmRestApi() - { - } - - /// Initializes a new instance of RestApi. - /// The origin of the operation. - /// The name of the operation. - /// The display name of the operation. - /// The display name of the resource the operation applies to. - /// The description of the operation. - /// The resource provider for the operation. - internal ArmRestApi(string origin, string name, string operation, string resource, string description, string provider) - { - Origin = origin; - Name = name; - Operation = operation; - Resource = resource; - Description = description; - Provider = provider; - } - - /// The origin of the operation. - public string Origin { get; } - /// The name of the operation. - public string Name { get; } - /// The display name of the operation. - public string Operation { get; } - /// The display name of the resource the operation applies to. - public string Resource { get; } - /// The description of the operation. - public string Description { get; } - /// The resource provider for the operation. - public string Provider { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApiListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApiListResult.Serialization.cs deleted file mode 100644 index ab24d2f204..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApiListResult.Serialization.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class ArmRestApiListResult - { - internal static ArmRestApiListResult DeserializeComputeOperationListResult(JsonElement element) - { - IReadOnlyList value = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value")) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ArmRestApi.DeserializeArmRestApi(item)); - } - value = array; - continue; - } - } - return new ArmRestApiListResult(value ?? new ChangeTrackingList()); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApiListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApiListResult.cs deleted file mode 100644 index 884cd877eb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApiListResult.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The List Operation operation response. - internal partial class ArmRestApiListResult - { - /// Initializes a new instance of RestApiListResult. - internal ArmRestApiListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of RestApiListResult. - /// The list of operations. - internal ArmRestApiListResult(IReadOnlyList value) - { - Value = value; - } - - /// The list of operations. - public IReadOnlyList Value { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/EnforcementMode.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/EnforcementMode.cs deleted file mode 100644 index ccb5c3feb6..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/EnforcementMode.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The policy assignment enforcement mode. Possible values are Default and DoNotEnforce. - public readonly partial struct EnforcementMode : IEquatable - { - private const string EnforcedValue = "Default"; - - /// The policy effect is enforced during resource creation or update. - [EditorBrowsable(EditorBrowsableState.Never)] - public static EnforcementMode Enforced { get; } = new EnforcementMode(EnforcedValue); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/LocationExpanded.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/LocationExpanded.cs deleted file mode 100644 index e585737abe..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/LocationExpanded.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.Collections.Generic; -using Azure.Core; - -[assembly:CodeGenSuppressType("CreatedByType")] -[assembly:CodeGenSuppressType("PolicyAssignmentIdentityType")] -[assembly:CodeGenSuppressType("PolicyAssignmentIdentityTypeExtensions")] -[assembly:CodeGenSuppressType("CloudError")] -namespace Azure.ResourceManager.Resources.Models -{ - public partial class LocationExpanded - { - /// - /// Convert LocationExpanded into a Location object. - /// - /// The location to convert. - public static implicit operator AzureLocation(LocationExpanded location) - { - return new AzureLocation(location.Name, location.DisplayName); - } - - /// Initializes a new instance of LocationExpanded. - /// The fully qualified ID of the location. For example, /subscriptions/00000000-0000-0000-0000-000000000000/locations/westus. - /// The subscription ID. - /// The location name. - /// The location type. - /// The display name of the location. - /// The display name of the location and its region. - /// Metadata of the location, such as lat/long, paired region, and others. - /// The availability zone mappings for this region. - internal LocationExpanded(string id, string subscriptionId, string name, LocationType? locationType, string displayName, string regionalDisplayName, LocationMetadata metadata, IReadOnlyList availabilityZoneMappings) - { - Id = id; - ResourceIdentifier subId = new ResourceIdentifier(id); - SubscriptionId = subscriptionId ?? subId.SubscriptionId; - Name = name; - LocationType = locationType; - DisplayName = displayName; - RegionalDisplayName = regionalDisplayName; - Metadata = metadata; - AvailabilityZoneMappings = availabilityZoneMappings; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/LocationMetadata.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/LocationMetadata.cs deleted file mode 100644 index f266b21d35..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/LocationMetadata.cs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System.ClientModel.Primitives; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - [CodeGenSerialization(nameof(Longitude), SerializationValueHook = nameof(WriteLongitude), DeserializationValueHook = nameof(ReadLongitude))] - [CodeGenSerialization(nameof(Latitude), SerializationValueHook = nameof(WriteLatitude), DeserializationValueHook = nameof(ReadLatitude))] - public partial class LocationMetadata - { - /// The longitude of the location. - public double? Longitude { get; } - /// The latitude of the location. - public double? Latitude { get; } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void WriteLongitude(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - if (Longitude.HasValue) - { - writer.WriteStringValue(Longitude.Value.ToString(CultureInfo.InvariantCulture)); - } - else - { - writer.WriteNullValue(); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static void ReadLongitude(JsonProperty property, ref double? longitude) - { - if (property.Value.ValueKind == JsonValueKind.Null) - return; - - longitude = double.Parse(property.Value.GetString(), CultureInfo.InvariantCulture); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void WriteLatitude(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - if (Latitude.HasValue) - { - writer.WriteStringValue(Latitude.Value.ToString(CultureInfo.InvariantCulture)); - } - else - { - writer.WriteNullValue(); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static void ReadLatitude(JsonProperty property, ref double? latitude) - { - if (property.Value.ValueKind == JsonValueKind.Null) - return; - - latitude = double.Parse(property.Value.GetString(), CultureInfo.InvariantCulture); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ResourcesMoveContent.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ResourcesMoveContent.cs deleted file mode 100644 index c63ec6232d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ResourcesMoveContent.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System.ComponentModel; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourcesMoveContent - { - /// The target resource group. - [EditorBrowsable(EditorBrowsableState.Never)] - public string TargetResourceGroup { get => TargetResourceGroupId.ToString(); set => TargetResourceGroupId = new ResourceIdentifier(value); } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ResourcesSku.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ResourcesSku.cs deleted file mode 100644 index 41b1f3e925..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/ResourcesSku.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - [CodeGenType("ResourceManagerSku")] - public partial class ResourcesSku - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/SubResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/SubResource.Serialization.cs deleted file mode 100644 index c6c9a86519..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/SubResource.Serialization.cs +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - [JsonConverter(typeof(SubResourceConverter))] - public partial class SubResource : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, new ModelReaderWriterOptions("W")); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SubResource)} does not support '{format}' format."); - } - - writer.WriteStartObject(); - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - writer.WriteEndObject(); - } - - SubResource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SubResource)} does not support '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeSubResource(document.RootElement, options); - } - - internal static SubResource DeserializeSubResource(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= new ModelReaderWriterOptions("W"); - - ResourceIdentifier id = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id")) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - } - return new SubResource(id); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(SubResource)} does not support '{options.Format}' format."); - } - } - - SubResource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeSubResource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(SubResource)} does not support '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class SubResourceConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, SubResource model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model); - } - public override SubResource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeSubResource(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/SubResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/SubResource.cs deleted file mode 100644 index 4677811ac4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/SubResource.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// - /// A class representing a sub-resource that contains only the read-only ID. - /// - [PropertyReferenceType] - public partial class SubResource - { - /// - /// Initializes an empty instance of for mocking. - /// - [InitializationConstructor] - public SubResource() - { - } - - /// Initializes a new instance of . - /// ARM resource Id. - [SerializationConstructor] - protected internal SubResource(ResourceIdentifier id) - { - Id = id; - } - - /// - /// Gets the ARM resource identifier. - /// - /// - public virtual ResourceIdentifier Id { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/Tag.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/Tag.cs deleted file mode 100644 index de31694444..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/Tag.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// A dictionary of name and value pairs. - public partial class Tag - { - /// Dictionary of <string>. - [CodeGenMember("Tags")] - public IDictionary TagValues { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/WritableSubResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/WritableSubResource.Serialization.cs deleted file mode 100644 index b44b3de3e9..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/WritableSubResource.Serialization.cs +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// - /// A class representing a sub-resource that contains only the ID. - /// - [JsonConverter(typeof(WritableSubResourceConverter))] - public partial class WritableSubResource : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, new ModelReaderWriterOptions("W")); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(WritableSubResource)} does not support '{format}' format."); - } - - writer.WriteStartObject(); - if (Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"); - writer.WriteStringValue(Id); - } - writer.WriteEndObject(); - } - - WritableSubResource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(WritableSubResource)} does not support '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeWritableSubResource(document.RootElement, options); - } - - /// - /// Deserialize the input JSON element to a WritableSubResource object. - /// - /// The JSON element to be deserialized. - /// The options to use. - /// Deserialized WritableSubResource object. - internal static WritableSubResource DeserializeWritableSubResource(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= new ModelReaderWriterOptions("W"); - - ResourceIdentifier id = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id")) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - } - return new WritableSubResource(id); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(WritableSubResource)} does not support '{options.Format}' format."); - } - } - - WritableSubResource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeWritableSubResource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(WritableSubResource)} does not support '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class WritableSubResourceConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, WritableSubResource model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model); - } - public override WritableSubResource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeWritableSubResource(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/WritableSubResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/WritableSubResource.cs deleted file mode 100644 index 105741ada8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/Models/WritableSubResource.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// - /// A class representing a sub-resource that contains only the ID. - /// - [PropertyReferenceType] - public partial class WritableSubResource - { - /// - /// Initializes an empty instance of for mocking. - /// - [InitializationConstructor] - public WritableSubResource() - { - } - - /// Initializes a new instance of . - /// ARM resource Id. - [SerializationConstructor] - protected internal WritableSubResource(ResourceIdentifier id) - { - Id = id; - } - - /// - /// Gets or sets the ARM resource identifier. - /// - /// - public ResourceIdentifier Id { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/PolicyAssignmentData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/PolicyAssignmentData.cs deleted file mode 100644 index 0889491a1a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/PolicyAssignmentData.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ComponentModel; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// A class representing the PolicyAssignment data model. - public partial class PolicyAssignmentData : ResourceData - { -#pragma warning disable CS0618 // This type is obsolete and will be removed in a future release. - private SystemAssignedServiceIdentity _identity; - /// The managed identity associated with the policy assignment. - [Obsolete("This property is obsolete and will be removed in a future release. Please use ManagedIdentity.", false)] - [EditorBrowsable(EditorBrowsableState.Never)] - public SystemAssignedServiceIdentity Identity - { - get - { - if (ManagedIdentity != null) - { - if (_identity == null || _identity.Identity != ManagedIdentity) - { - _identity = new SystemAssignedServiceIdentity(ManagedIdentity); - } - } - else - { - _identity = null; - } - return _identity; - } - set - { - _identity = value; - ManagedIdentity = value == null ? null : _identity.Identity; - } - } -#pragma warning restore CS0618 // This type is obsolete and will be removed in a future release. - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/PolicyAssignmentResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/PolicyAssignmentResource.cs deleted file mode 100644 index b658d222e0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/PolicyAssignmentResource.cs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class PolicyAssignmentResource - { - /// - /// This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Create - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Parameters for the policy assignment. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(WaitUntil waitUntil, PolicyAssignmentData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentResource.Update"); - scope.Start(); - try - { - var response = await _policyAssignmentRestClient.CreateAsync(Id.Parent, Id.Name, data, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(Response.FromValue(new PolicyAssignmentResource(Client, response), response.GetRawResponse())); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Create - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Parameters for the policy assignment. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation Update(WaitUntil waitUntil, PolicyAssignmentData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentResource.Update"); - scope.Start(); - try - { - var response = _policyAssignmentRestClient.Create(Id.Parent, Id.Name, data, cancellationToken); - var operation = new ResourcesArmOperation(Response.FromValue(new PolicyAssignmentResource(Client, response), response.GetRawResponse())); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceGroupBuilder.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceGroupBuilder.cs deleted file mode 100644 index 22cc3f1726..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceGroupBuilder.cs +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a builder object used to create Azure resources. - /// - internal class ResourceGroupBuilder - { - /// - /// Initializes a new instance of the class. - /// - /// The collection object to create the resource in. - /// The resource to create. - public ResourceGroupBuilder(ResourceGroupCollection collection, ResourceGroupData resource) - { - Resource = resource; - Collection = collection; - } - - /// - /// Gets the resource object to create. - /// - protected ResourceGroupData Resource { get; private set; } - - /// - /// Gets the resource name. - /// - protected string ResourceName { get; private set; } - - /// - /// Gets the collection object to create the resource in. - /// - protected ResourceGroupCollection Collection { get; private set; } - - /// - /// Creates the resource object to send to the Azure API. - /// - /// The resource to create. - public ResourceGroupData Build() - { - ThrowIfNotValid(); - OnBeforeBuild(); - InternalBuild(); - OnAfterBuild(); - - return Resource; - } - - /// - /// The operation to create or update a resource. Please note some properties can be set only during creation. - /// - /// The name of the new resource to create. - /// Waits for the completion of the long running operations. - /// A token to allow the caller to cancel the call to the service. The default value is . - /// A response with the operation for this resource. - /// Name cannot be null or a whitespace. - public ArmOperation CreateOrUpdate(string name, WaitUntil waitUntil = WaitUntil.Completed, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(name)) - throw new ArgumentException("Name cannot be null or whitespace.", nameof(name)); - - ResourceName = name; - Resource = Build(); - - return Collection.CreateOrUpdate(waitUntil, name, Resource, cancellationToken); - } - - /// - /// The operation to create or update a resource. Please note some properties can be set only during creation. - /// - /// The name of the new resource to create. - /// Waits for the completion of the long running operations. - /// A token to allow the caller to cancel the call to the service. The default value is . - /// A that on completion returns a response with the operation for this resource. - /// Name cannot be null or a whitespace. - public async Task> CreateOrUpdateAsync(string name, WaitUntil waitUntil = WaitUntil.Completed, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(name)) - throw new ArgumentException("Name cannot be null or whitespace.", nameof(name)); - - ResourceName = name; - Resource = Build(); - - return await Collection.CreateOrUpdateAsync(waitUntil, name, Resource, cancellationToken).ConfigureAwait(false); - } - - /// - /// Determines whether or not the resource is valid. - /// - /// The message indicating what is wrong with the resource. - /// Whether or not the resource is valid. - protected virtual bool IsValid(out string message) - { - message = string.Empty; - - return true; - } - - /// - /// Perform any tasks necessary after the resource is built. - /// - protected virtual void OnAfterBuild() - { - } - - /// - /// Perform any tasks necessary before the resource is built. - /// - protected virtual void OnBeforeBuild() - { - } - - private static void InternalBuild() - { - } - - private void ThrowIfNotValid() - { - if (!IsValid(out var message)) - { - throw new InvalidOperationException(message); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceGroupCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceGroupCollection.cs deleted file mode 100644 index cf7e8bb395..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceGroupCollection.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Threading; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// A class representing collection of ResourceGroupResource and their operations over its parent. - [CodeGenSuppress("GetAllAsGenericResources", typeof(string), typeof(string), typeof(int?), typeof(CancellationToken))] - [CodeGenSuppress("GetAllAsGenericResourcesAsync", typeof(string), typeof(string), typeof(int?), typeof(CancellationToken))] - public partial class ResourceGroupCollection : ArmCollection, IEnumerable, IAsyncEnumerable - - { - /// - /// Constructs an object used to create a resource group. - /// - /// The location of the resource group. - /// The tags of the resource group. - /// Who the resource group is managed by. - /// A builder with and . - /// Location cannot be null. - internal ResourceGroupBuilder Construct(AzureLocation location, IDictionary tags = default, string managedBy = default) - { - var model = new ResourceGroupData(location); - if (!(tags is null)) - model.Tags.ReplaceWith(tags); - model.ManagedBy = managedBy; - return new ResourceGroupBuilder(this, model); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceGroupResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceGroupResource.cs deleted file mode 100644 index 75c02571f4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceGroupResource.cs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -[assembly:CodeGenSuppressType("ResourceGroupUpdateOperation")] -namespace Azure.ResourceManager.Resources -{ - /// A Class representing a ResourceGroupResource along with the instance operations that can be performed on it. - public partial class ResourceGroupResource : ArmResource - { - /// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/resources - /// ContextualPath: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// OperationId: Resources_ListByResourceGroup - /// Get all the resources for a resource group. - /// The filter to apply on the operation.<br><br>The properties you can use for eq (equals) or ne (not equals) are: location, resourceType, name, resourceGroup, identity, identity/principalId, plan, plan/publisher, plan/product, plan/name, plan/version, and plan/promotionCode.<br><br>For example, to filter by a resource type, use: $filter=resourceType eq 'Microsoft.Network/virtualNetworks'<br><br>You can use substringof(value, property) in the filter. The properties you can use for substring are: name and resourceGroup.<br><br>For example, to get all resources with 'demo' anywhere in the name, use: $filter=substringof('demo', name)<br><br>You can link more than one substringof together by adding and/or operators.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. When you filter by a tag name and value, the tags for each resource are not returned in the results.<br><br>You can use some properties together when filtering. The combinations you can use are: substringof and/or resourceType, plan and plan/publisher and plan/name, identity and identity/principalId. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of results to return. If null is passed, returns all resources. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetGenericResourcesAsync(string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - async Task> FirstPageFunc(int? pageSizeHint) - { - using var scope = _resourceGroupResourcesClientDiagnostics.CreateScope("ResourceGroupResource.GetGenericResources"); - scope.Start(); - try - { - var response = await _resourceGroupResourcesRestClient.ListByResourceGroupAsync(Id.SubscriptionId, Id.ResourceGroupName, filter, expand, top, cancellationToken: cancellationToken).ConfigureAwait(false); - return Page.FromValues(response.Value.Value.Select(value => new GenericResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - async Task> NextPageFunc(string nextLink, int? pageSizeHint) - { - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.GetGenericResources"); - scope.Start(); - try - { - var response = await _resourceGroupResourcesRestClient.ListByResourceGroupNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, filter, expand, top, cancellationToken: cancellationToken).ConfigureAwait(false); - return Page.FromValues(response.Value.Value.Select(value => new GenericResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); - } - - /// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/resources - /// ContextualPath: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// OperationId: Resources_ListByResourceGroup - /// Get all the resources for a resource group. - /// The filter to apply on the operation.<br><br>The properties you can use for eq (equals) or ne (not equals) are: location, resourceType, name, resourceGroup, identity, identity/principalId, plan, plan/publisher, plan/product, plan/name, plan/version, and plan/promotionCode.<br><br>For example, to filter by a resource type, use: $filter=resourceType eq 'Microsoft.Network/virtualNetworks'<br><br>You can use substringof(value, property) in the filter. The properties you can use for substring are: name and resourceGroup.<br><br>For example, to get all resources with 'demo' anywhere in the name, use: $filter=substringof('demo', name)<br><br>You can link more than one substringof together by adding and/or operators.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. When you filter by a tag name and value, the tags for each resource are not returned in the results.<br><br>You can use some properties together when filtering. The combinations you can use are: substringof and/or resourceType, plan and plan/publisher and plan/name, identity and identity/principalId. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of results to return. If null is passed, returns all resources. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetGenericResources(string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Page FirstPageFunc(int? pageSizeHint) - { - using var scope = _resourceGroupResourcesClientDiagnostics.CreateScope("ResourceGroupResource.GetGenericResources"); - scope.Start(); - try - { - var response = _resourceGroupResourcesRestClient.ListByResourceGroup(Id.SubscriptionId, Id.ResourceGroupName, filter, expand, top, cancellationToken: cancellationToken); - return Page.FromValues(response.Value.Value.Select(value => new GenericResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - Page NextPageFunc(string nextLink, int? pageSizeHint) - { - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.GetGenericResources"); - scope.Start(); - try - { - var response = _resourceGroupResourcesRestClient.ListByResourceGroupNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, filter, expand, top, cancellationToken: cancellationToken); - return Page.FromValues(response.Value.Value.Select(value => new GenericResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceManagerModelFactory.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceManagerModelFactory.cs deleted file mode 100644 index 73d3cdd844..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceManagerModelFactory.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Models -{ - /// Model factory for read-only models. - public static partial class ResourceManagerModelFactory - { - /// Initializes a new instance of SubResource. - /// - /// A new instance for mocking. - public static SubResource SubResource(ResourceIdentifier id = null) - { - return new SubResource(id); - } - - /// Initializes a new instance of WritableSubResource. - /// - /// A new instance for mocking. - public static WritableSubResource WritableSubResource(ResourceIdentifier id = null) - { - return new WritableSubResource(id); - } - - /// Initializes a new instance of LocationExpanded. - /// The fully qualified ID of the location. For example, /subscriptions/00000000-0000-0000-0000-000000000000/locations/westus. - /// The subscription ID. - /// The location name. - /// The location type. - /// The display name of the location. - /// The display name of the location and its region. - /// Metadata of the location, such as lat/long, paired region, and others. - /// A new instance for mocking. - public static LocationExpanded LocationExpanded(string id, string subscriptionId, string name, LocationType? locationType, string displayName, string regionalDisplayName, LocationMetadata metadata) - { - return new LocationExpanded(id, subscriptionId, name, locationType, displayName, regionalDisplayName, metadata, null); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceProviderCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceProviderCollection.cs deleted file mode 100644 index c883e46b6d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceProviderCollection.cs +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// A class representing collection of Provider and their operations over its parent. - [CodeGenSuppress("GetAllAsGenericResources", typeof(string), typeof(string), typeof(int?), typeof(CancellationToken))] - [CodeGenSuppress("GetAllAsGenericResourcesAsync", typeof(string), typeof(string), typeof(int?), typeof(CancellationToken))] - public partial class ResourceProviderCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - /// Initializes a new instance of the class. - /// The resource representing the parent resource. - internal ResourceProviderCollection(ArmResource parent) : this(parent.Client, parent.Id) - { - } - - internal ResourceProviderCollection(ArmClient client, ResourceIdentifier id) - : base(client, id) - { - _resourceProviderProvidersClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceProviderResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceProviderResource.ResourceType, out string providerApiVersion); - _resourceProviderProvidersRestClient = new ProvidersRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, providerApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - [ForwardsClientCalls(true)] - internal virtual string GetApiVersion(ResourceType resourceType, CancellationToken cancellationToken = default) - { - string version; - Dictionary resourceVersions; - if (!Client.ApiVersionOverrides.TryGetValue(resourceType, out version)) - { - if (!Client.ResourceApiVersionCache.TryGetValue(resourceType.Namespace, out resourceVersions)) - { - resourceVersions = LoadResourceVersionsFromApi(resourceType.Namespace, cancellationToken); - Client.ResourceApiVersionCache.TryAdd(resourceType.Namespace, resourceVersions); - } - if (!resourceVersions.TryGetValue(resourceType.Type, out version)) - { - throw new InvalidOperationException($"Invalid resource type {resourceType}"); - } - } - return version; - } - - [ForwardsClientCalls(true)] - internal virtual async ValueTask GetApiVersionAsync(ResourceType resourceType, CancellationToken cancellationToken = default) - { - string version; - Dictionary resourceVersions; - if (!Client.ApiVersionOverrides.TryGetValue(resourceType, out version)) - { - if (!Client.ResourceApiVersionCache.TryGetValue(resourceType.Namespace, out resourceVersions)) - { - resourceVersions = await LoadResourceVersionsFromApiAsync(resourceType.Namespace, cancellationToken).ConfigureAwait(false); - Client.ResourceApiVersionCache.TryAdd(resourceType.Namespace, resourceVersions); - } - if (!resourceVersions.TryGetValue(resourceType.Type, out version)) - { - throw new InvalidOperationException($"Invalid resource type {resourceType}"); - } - } - return version; - } - - private Dictionary LoadResourceVersionsFromApi(string resourceNamespace, CancellationToken cancellationToken = default) - { - ResourceProviderResource results = Get(resourceNamespace, cancellationToken: cancellationToken); - return GetVersionsFromResult(results); - } - - private async Task> LoadResourceVersionsFromApiAsync(string resourceNamespace, CancellationToken cancellationToken = default) - { - ResourceProviderResource results = await GetAsync(resourceNamespace, cancellationToken: cancellationToken).ConfigureAwait(false); - return GetVersionsFromResult(results); - } - - private static Dictionary GetVersionsFromResult(ResourceProviderResource results) - { - Dictionary resourceVersions = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (var type in results.Data.ResourceTypes) - { - if (type.ApiVersions.Count == 0) - continue; - resourceVersions[type.ResourceType] = type.ApiVersions[0]; - } - return resourceVersions; - } - - /// - /// Gets all resource providers for a subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers - /// - /// - /// Operation Id - /// Providers_List - /// - /// - /// - /// [This parameter is no longer supported.] The number of results to return. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("This method is obsolete as the `top` parameter is not supported by service and will be removed in a future release.", false)] - public virtual AsyncPageable GetAllAsync(int? top, string expand, CancellationToken cancellationToken = default) - { - return GetAllAsync(expand, cancellationToken); - } - - /// - /// Gets all resource providers for a subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers - /// - /// - /// Operation Id - /// Providers_List - /// - /// - /// - /// [This parameter is no longer supported.] The number of results to return. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("This method is obsolete as the `top` parameter is not supported by service and will be removed in a future release.", false)] - public virtual Pageable GetAll(int? top, string expand, CancellationToken cancellationToken = default) - { - return GetAll(expand, cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceProviderData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceProviderData.cs deleted file mode 100644 index 7081df7c19..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceProviderData.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// A class representing the Provider data model. - [PropertyReferenceType] - [JsonConverter(typeof(ProviderDataConverter))] - public partial class ResourceProviderData - { - /// Initializes a new instance of ProviderData. - [InitializationConstructor] - public ResourceProviderData() - { - ResourceTypes = new ChangeTrackingList(); - } - - /// Initializes a new instance of ProviderData. - /// The provider ID. - /// The namespace of the resource provider. - /// The registration state of the resource provider. - /// The registration policy of the resource provider. - /// The collection of provider resource types. - /// The provider authorization consent state. - [SerializationConstructor] - internal ResourceProviderData(ResourceIdentifier id, string @namespace, string registrationState, string registrationPolicy, IReadOnlyList resourceTypes, ProviderAuthorizationConsentState? providerAuthorizationConsentState) - { - Id = id; - Namespace = @namespace; - RegistrationState = registrationState; - RegistrationPolicy = registrationPolicy; - ResourceTypes = resourceTypes; - ProviderAuthorizationConsentState = providerAuthorizationConsentState; - } - - /// The provider ID. - public ResourceIdentifier Id { get; } - - internal partial class ProviderDataConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, ResourceProviderData providerData, JsonSerializerOptions options) - { - writer.WriteObjectValue(providerData); - } - public override ResourceProviderData Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceProviderData(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceProviderResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceProviderResource.cs deleted file mode 100644 index d31340bbca..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/ResourceProviderResource.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Threading; -using Azure.Core; - -namespace Azure.ResourceManager.Resources -{ - /// A Class representing a Provider along with the instance operations that can be performed on it. - [CodeGenSuppress("GetAvailableLocations", typeof(CancellationToken))] - [CodeGenSuppress("GetAvailableLocationsAsync", typeof(CancellationToken))] - public partial class ResourceProviderResource : ArmResource - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/RestOperations/RestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/RestOperations/RestOperations.cs deleted file mode 100644 index 9652d2393f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/RestOperations/RestOperations.cs +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class RestOperations - { - private Uri endpoint; - private string apiVersion; - private ClientDiagnostics _clientDiagnostics; - private HttpPipeline _pipeline; - private string _nameSpace; - private readonly TelemetryDetails _userAgent; - - /// Initializes a new instance of RestOperations. - /// The namespace to get the operations for. - /// The handler for diagnostic messaging in the client. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The client options used to construct the current client. - /// server parameter. - /// Api Version. - /// is null. - public RestOperations(string nameSpace, string apiVersion, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string applicationId, Uri endpoint = null) - { - endpoint ??= new Uri("https://management.azure.com"); - if (apiVersion == null) - { - throw new ArgumentNullException(nameof(apiVersion)); - } - - this.endpoint = endpoint; - this.apiVersion = apiVersion; - _clientDiagnostics = clientDiagnostics; - _pipeline = pipeline; - _nameSpace = nameSpace; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal HttpMessage CreateListRequest() - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(endpoint); - uri.AppendPath($"/providers/{_nameSpace}/operations", false); - uri.AppendQuery("api-version", apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets a list of operations. - /// The cancellation token to use. - public async Task> ListAsync(CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ArmRestApiListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); - value = ArmRestApiListResult.DeserializeComputeOperationListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets a list of operations. - /// The cancellation token to use. - public Response List(CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ArmRestApiListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream); - value = ArmRestApiListResult.DeserializeComputeOperationListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/RestOperations/TenantsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/RestOperations/TenantsRestOperations.cs deleted file mode 100644 index a04a4128ac..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/RestOperations/TenantsRestOperations.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Threading; -using Azure.Core; - -namespace Azure.ResourceManager.Resources -{ - [CodeGenSuppress("Get", typeof(CancellationToken))] - [CodeGenSuppress("GetAsync", typeof(CancellationToken))] - [CodeGenSuppress("CreateGetRequest")] - internal partial class TenantsRestOperations - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/SubscriptionData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/SubscriptionData.cs deleted file mode 100644 index 01db245a68..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/SubscriptionData.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using Azure.Core; - -namespace Azure.ResourceManager.Resources -{ - /// A class representing the Subscription data model. - public partial class SubscriptionData - { - /// The ARM resource identifier. - public virtual ResourceIdentifier Id { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/SubscriptionResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/SubscriptionResource.cs deleted file mode 100644 index db043c39c0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/SubscriptionResource.cs +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.ComponentModel; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the operations that can be performed over a specific subscription. - /// - public partial class SubscriptionResource : ArmResource - { - /// RequestPath: /subscriptions/{subscriptionId}/resources - /// ContextualPath: /subscriptions/{subscriptionId} - /// OperationId: Resources_List - /// Get all the resources in a subscription. - /// The filter to apply on the operation.<br><br>The properties you can use for eq (equals) or ne (not equals) are: location, resourceType, name, resourceGroup, identity, identity/principalId, plan, plan/publisher, plan/product, plan/name, plan/version, and plan/promotionCode.<br><br>For example, to filter by a resource type, use: $filter=resourceType eq 'Microsoft.Network/virtualNetworks'<br><br>You can use substringof(value, property) in the filter. The properties you can use for substring are: name and resourceGroup.<br><br>For example, to get all resources with 'demo' anywhere in the name, use: $filter=substringof('demo', name)<br><br>You can link more than one substringof together by adding and/or operators.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. When you filter by a tag name and value, the tags for each resource are not returned in the results.<br><br>You can use some properties together when filtering. The combinations you can use are: substringof and/or resourceType, plan and plan/publisher and plan/name, identity and identity/principalId. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of results to return. If null is passed, returns all resource groups. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetGenericResourcesAsync(string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - async Task> FirstPageFunc(int? pageSizeHint) - { - using var scope = _subscriptionClientDiagnostics.CreateScope("SubscriptionResource.GetGenericResources"); - scope.Start(); - try - { - var response = await _subscriptionResourcesRestClient.ListAsync(Id.SubscriptionId, filter, expand, top, cancellationToken: cancellationToken).ConfigureAwait(false); - return Page.FromValues(response.Value.Value.Select(value => new GenericResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - async Task> NextPageFunc(string nextLink, int? pageSizeHint) - { - using var scope = _subscriptionResourcesClientDiagnostics.CreateScope("SubscriptionResource.GetGenericResources"); - scope.Start(); - try - { - var response = await _subscriptionResourcesRestClient.ListNextPageAsync(nextLink, Id.SubscriptionId, filter, expand, top, cancellationToken: cancellationToken).ConfigureAwait(false); - return Page.FromValues(response.Value.Value.Select(value => new GenericResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); - } - - /// RequestPath: /subscriptions/{subscriptionId}/resources - /// ContextualPath: /subscriptions/{subscriptionId} - /// OperationId: Resources_List - /// Get all the resources in a subscription. - /// The filter to apply on the operation.<br><br>The properties you can use for eq (equals) or ne (not equals) are: location, resourceType, name, resourceGroup, identity, identity/principalId, plan, plan/publisher, plan/product, plan/name, plan/version, and plan/promotionCode.<br><br>For example, to filter by a resource type, use: $filter=resourceType eq 'Microsoft.Network/virtualNetworks'<br><br>You can use substringof(value, property) in the filter. The properties you can use for substring are: name and resourceGroup.<br><br>For example, to get all resources with 'demo' anywhere in the name, use: $filter=substringof('demo', name)<br><br>You can link more than one substringof together by adding and/or operators.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. When you filter by a tag name and value, the tags for each resource are not returned in the results.<br><br>You can use some properties together when filtering. The combinations you can use are: substringof and/or resourceType, plan and plan/publisher and plan/name, identity and identity/principalId. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of results to return. If null is passed, returns all resource groups. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetGenericResources(string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Page FirstPageFunc(int? pageSizeHint) - { - using var scope = _subscriptionResourcesClientDiagnostics.CreateScope("SubscriptionResource.GetGenericResources"); - scope.Start(); - try - { - var response = _subscriptionResourcesRestClient.List(Id.SubscriptionId, filter, expand, top, cancellationToken: cancellationToken); - return Page.FromValues(response.Value.Value.Select(value => new GenericResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - Page NextPageFunc(string nextLink, int? pageSizeHint) - { - using var scope = _subscriptionResourcesClientDiagnostics.CreateScope("SubscriptionResource.GetGenericResources"); - scope.Start(); - try - { - var response = _subscriptionResourcesRestClient.ListNextPage(nextLink, Id.SubscriptionId, filter, expand, top, cancellationToken: cancellationToken); - return Page.FromValues(response.Value.Value.Select(value => new GenericResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); - } - - /// - /// Gets the RestApi definition for a given Azure namespace. - /// - /// The namespace to get the rest API for. - /// A collection representing the rest apis for the namespace. - public virtual ArmRestApiCollection GetArmRestApis(string azureNamespace) - { - return new ArmRestApiCollection(this, azureNamespace); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/TagResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/TagResource.cs deleted file mode 100644 index a8e6740e55..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/TagResource.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a TagResource along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetTagResource method. - /// Otherwise you can get one from its parent resource using the GetTagResource method. - /// - public partial class TagResource : ArmResource - { - /// - /// This operation allows replacing, merging or selectively deleting tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags at the end of the operation. The 'replace' option replaces the entire set of existing tags with a new set. The 'merge' option allows adding tags with new names and updating the values of tags with existing names. The 'delete' option allows selectively deleting tags based on given names or name/value pairs. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_UpdateAtScope - /// - /// - /// - /// The TagResourcePatch to use. - /// The cancellation token to use. - /// is null. - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("This method is obsolete and will be removed in a future release.", false)] - public virtual async Task> UpdateAsync(TagResourcePatch patch, CancellationToken cancellationToken = default) - { - var operation = await UpdateAsync(WaitUntil.Completed, patch, cancellationToken).ConfigureAwait(false); - return Response.FromValue(operation.Value, operation.GetRawResponse()); - } - - /// - /// This operation allows replacing, merging or selectively deleting tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags at the end of the operation. The 'replace' option replaces the entire set of existing tags with a new set. The 'merge' option allows adding tags with new names and updating the values of tags with existing names. The 'delete' option allows selectively deleting tags based on given names or name/value pairs. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_UpdateAtScope - /// - /// - /// - /// The TagResourcePatch to use. - /// The cancellation token to use. - /// is null. - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("This method is obsolete and will be removed in a future release.", false)] - public virtual Response Update(TagResourcePatch patch, CancellationToken cancellationToken = default) - { - var operation = Update(WaitUntil.Completed, patch, cancellationToken); - return Response.FromValue(operation.Value, operation.GetRawResponse()); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/TenantCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/TenantCollection.cs deleted file mode 100644 index 9a4f57e413..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/TenantCollection.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.Collections.Generic; -using System.Threading; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing collection of TenantResource and their operations over their parent. - /// - [CodeGenSuppress("Get", typeof(CancellationToken))] - [CodeGenSuppress("GetAsync", typeof(CancellationToken))] - [CodeGenSuppress("Exists", typeof(CancellationToken))] - [CodeGenSuppress("ExistsAsync", typeof(CancellationToken))] - [CodeGenSuppress("GetIfExists", typeof(CancellationToken))] - [CodeGenSuppress("GetIfExistsAsync", typeof(CancellationToken))] - public partial class TenantCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - /// Initializes a new instance of the class. - /// The resource representing the parent resource. - internal TenantCollection(ArmClient client) : this(client, ResourceIdentifier.Root) - { - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/TenantResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/TenantResource.cs deleted file mode 100644 index 6fadc0c833..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Custom/TenantResource.cs +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -[assembly: CodeGenSuppressType("TenantExtensions")] -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the operations that can be performed over a specific subscription. - /// - [CodeGenSuppress("TenantResource", typeof(ArmClient), typeof(TenantData))] - [CodeGenSuppress("Get", typeof(CancellationToken))] - [CodeGenSuppress("GetAsync", typeof(CancellationToken))] - [CodeGenSuppress("GetAvailableLocations", typeof(CancellationToken))] - [CodeGenSuppress("GetAvailableLocationsAsync", typeof(CancellationToken))] - [CodeGenSuppress("GetTenants")] - [CodeGenSuppress("CreateResourceIdentifier")] - [CodeGenSuppress("GetGenericResourceAsync", typeof(ResourceIdentifier), typeof(string), typeof(CancellationToken))] - [CodeGenSuppress("GetGenericResource", typeof(ResourceIdentifier), typeof(string), typeof(CancellationToken))] - // [CodeGenSuppress("_tenantsRestClient")] // TODO: not working for private member - public partial class TenantResource : ArmResource - { - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - internal TenantResource(ArmClient client) : this(client, ResourceIdentifier.Root) - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal TenantResource(ArmClient client, TenantData data) : this(client, ResourceIdentifier.Root) - { - HasData = true; - _data = data; - } - - /// - /// Gets all resource providers for the tenant. - /// - /// - /// Request Path - /// /providers - /// - /// - /// Operation Id - /// Providers_ListAtTenantScope - /// - /// - /// - /// [This parameter is no longer supported.] The number of results to return. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("This method is obsolete as the `top` parameter is not supported by service and will be removed in a future release.", false)] - public virtual AsyncPageable GetTenantResourceProvidersAsync(int? top, string expand, CancellationToken cancellationToken = default) - { - return GetTenantResourceProvidersAsync(expand, cancellationToken); - } - - /// - /// Gets all resource providers for the tenant. - /// - /// - /// Request Path - /// /providers - /// - /// - /// Operation Id - /// Providers_ListAtTenantScope - /// - /// - /// - /// [This parameter is no longer supported.] The number of results to return. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("This method is obsolete as the `top` parameter is not supported by service and will be removed in a future release.", false)] - public virtual Pageable GetTenantResourceProviders(int? top, string expand, CancellationToken cancellationToken = default) - { - return GetTenantResourceProviders(expand, cancellationToken); - } - - /// - /// Gets a resource by ID. - /// - /// - /// Request Path - /// /{resourceId} - /// - /// - /// Operation Id - /// Resources_GetById - /// - /// - /// - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The cancellation token to use. - /// is null. - // api-version is defined as method parameter in spec but used as client parameter for Resources_GetById to keep the contract unchaged - [ForwardsClientCalls] - public virtual async Task> GetGenericResourceAsync(ResourceIdentifier resourceId, CancellationToken cancellationToken = default) - { - return await GetGenericResources().GetAsync(resourceId, cancellationToken).ConfigureAwait(false); - } - - /// - /// Gets a resource by ID. - /// - /// - /// Request Path - /// /{resourceId} - /// - /// - /// Operation Id - /// Resources_GetById - /// - /// - /// - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The cancellation token to use. - /// is null. - // api-version is defined as method parameter in spec but used as client parameter for Resources_GetById to keep the contract unchaged - [ForwardsClientCalls] - public virtual Response GetGenericResource(ResourceIdentifier resourceId, CancellationToken cancellationToken = default) - { - return GetGenericResources().Get(resourceId, cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestCollection.cs deleted file mode 100644 index 3d94174f1d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestCollection.cs +++ /dev/null @@ -1,396 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetDataPolicyManifests method from an instance of . - /// - public partial class DataPolicyManifestCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _dataPolicyManifestClientDiagnostics; - private readonly DataPolicyManifestsRestOperations _dataPolicyManifestRestClient; - - /// Initializes a new instance of the class for mocking. - protected DataPolicyManifestCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal DataPolicyManifestCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _dataPolicyManifestClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", DataPolicyManifestResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(DataPolicyManifestResource.ResourceType, out string dataPolicyManifestApiVersion); - _dataPolicyManifestRestClient = new DataPolicyManifestsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, dataPolicyManifestApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != TenantResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, TenantResource.ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the data policy manifest with the given policy mode. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string policyMode, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyMode, nameof(policyMode)); - - using var scope = _dataPolicyManifestClientDiagnostics.CreateScope("DataPolicyManifestCollection.Get"); - scope.Start(); - try - { - var response = await _dataPolicyManifestRestClient.GetByPolicyModeAsync(policyMode, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new DataPolicyManifestResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the data policy manifest with the given policy mode. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string policyMode, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyMode, nameof(policyMode)); - - using var scope = _dataPolicyManifestClientDiagnostics.CreateScope("DataPolicyManifestCollection.Get"); - scope.Start(); - try - { - var response = _dataPolicyManifestRestClient.GetByPolicyMode(policyMode, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new DataPolicyManifestResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a list of all the data policy manifests that match the optional given $filter. Valid values for $filter are: "$filter=namespace eq '{0}'". If $filter is not provided, the unfiltered list includes all data policy manifests for data resource types. If $filter=namespace is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests - /// - /// - /// Operation Id - /// DataPolicyManifests_List - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: "namespace eq '{value}'". If $filter is not provided, no filtering is performed. If $filter=namespace eq '{value}' is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _dataPolicyManifestRestClient.CreateListRequest(filter); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _dataPolicyManifestRestClient.CreateListNextPageRequest(nextLink, filter); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new DataPolicyManifestResource(Client, DataPolicyManifestData.DeserializeDataPolicyManifestData(e)), _dataPolicyManifestClientDiagnostics, Pipeline, "DataPolicyManifestCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// This operation retrieves a list of all the data policy manifests that match the optional given $filter. Valid values for $filter are: "$filter=namespace eq '{0}'". If $filter is not provided, the unfiltered list includes all data policy manifests for data resource types. If $filter=namespace is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests - /// - /// - /// Operation Id - /// DataPolicyManifests_List - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: "namespace eq '{value}'". If $filter is not provided, no filtering is performed. If $filter=namespace eq '{value}' is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _dataPolicyManifestRestClient.CreateListRequest(filter); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _dataPolicyManifestRestClient.CreateListNextPageRequest(nextLink, filter); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new DataPolicyManifestResource(Client, DataPolicyManifestData.DeserializeDataPolicyManifestData(e)), _dataPolicyManifestClientDiagnostics, Pipeline, "DataPolicyManifestCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string policyMode, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyMode, nameof(policyMode)); - - using var scope = _dataPolicyManifestClientDiagnostics.CreateScope("DataPolicyManifestCollection.Exists"); - scope.Start(); - try - { - var response = await _dataPolicyManifestRestClient.GetByPolicyModeAsync(policyMode, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string policyMode, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyMode, nameof(policyMode)); - - using var scope = _dataPolicyManifestClientDiagnostics.CreateScope("DataPolicyManifestCollection.Exists"); - scope.Start(); - try - { - var response = _dataPolicyManifestRestClient.GetByPolicyMode(policyMode, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string policyMode, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyMode, nameof(policyMode)); - - using var scope = _dataPolicyManifestClientDiagnostics.CreateScope("DataPolicyManifestCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _dataPolicyManifestRestClient.GetByPolicyModeAsync(policyMode, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new DataPolicyManifestResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string policyMode, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyMode, nameof(policyMode)); - - using var scope = _dataPolicyManifestClientDiagnostics.CreateScope("DataPolicyManifestCollection.GetIfExists"); - scope.Start(); - try - { - var response = _dataPolicyManifestRestClient.GetByPolicyMode(policyMode, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new DataPolicyManifestResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestData.Serialization.cs deleted file mode 100644 index fd2f9189ee..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestData.Serialization.cs +++ /dev/null @@ -1,647 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class DataPolicyManifestData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataPolicyManifestData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (Optional.IsCollectionDefined(Namespaces)) - { - writer.WritePropertyName("namespaces"u8); - writer.WriteStartArray(); - foreach (var item in Namespaces) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(PolicyMode)) - { - writer.WritePropertyName("policyMode"u8); - writer.WriteStringValue(PolicyMode); - } - if (Optional.IsDefined(IsBuiltInOnly)) - { - writer.WritePropertyName("isBuiltInOnly"u8); - writer.WriteBooleanValue(IsBuiltInOnly.Value); - } - if (Optional.IsCollectionDefined(ResourceTypeAliases)) - { - writer.WritePropertyName("resourceTypeAliases"u8); - writer.WriteStartArray(); - foreach (var item in ResourceTypeAliases) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(Effects)) - { - writer.WritePropertyName("effects"u8); - writer.WriteStartArray(); - foreach (var item in Effects) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(FieldValues)) - { - writer.WritePropertyName("fieldValues"u8); - writer.WriteStartArray(); - foreach (var item in FieldValues) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - writer.WritePropertyName("resourceFunctions"u8); - writer.WriteStartObject(); - if (Optional.IsCollectionDefined(Standard)) - { - writer.WritePropertyName("standard"u8); - writer.WriteStartArray(); - foreach (var item in Standard) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(CustomDefinitions)) - { - writer.WritePropertyName("custom"u8); - writer.WriteStartArray(); - foreach (var item in CustomDefinitions) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - writer.WriteEndObject(); - writer.WriteEndObject(); - } - - DataPolicyManifestData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataPolicyManifestData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDataPolicyManifestData(document.RootElement, options); - } - - internal static DataPolicyManifestData DeserializeDataPolicyManifestData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - IReadOnlyList namespaces = default; - string policyMode = default; - bool? isBuiltInOnly = default; - IReadOnlyList resourceTypeAliases = default; - IReadOnlyList effects = default; - IReadOnlyList fieldValues = default; - IReadOnlyList standard = default; - IReadOnlyList custom = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.SystemData); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("namespaces"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - namespaces = array; - continue; - } - if (property0.NameEquals("policyMode"u8)) - { - policyMode = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("isBuiltInOnly"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - isBuiltInOnly = property0.Value.GetBoolean(); - continue; - } - if (property0.NameEquals("resourceTypeAliases"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(Models.ResourceTypeAliases.DeserializeResourceTypeAliases(item, options)); - } - resourceTypeAliases = array; - continue; - } - if (property0.NameEquals("effects"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(DataPolicyManifestEffect.DeserializeDataPolicyManifestEffect(item, options)); - } - effects = array; - continue; - } - if (property0.NameEquals("fieldValues"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - fieldValues = array; - continue; - } - if (property0.NameEquals("resourceFunctions"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - property0.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property1 in property0.Value.EnumerateObject()) - { - if (property1.NameEquals("standard"u8)) - { - if (property1.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property1.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - standard = array; - continue; - } - if (property1.NameEquals("custom"u8)) - { - if (property1.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property1.Value.EnumerateArray()) - { - array.Add(DataManifestCustomResourceFunctionDefinition.DeserializeDataManifestCustomResourceFunctionDefinition(item, options)); - } - custom = array; - continue; - } - } - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new DataPolicyManifestData( - id, - name, - type, - systemData, - namespaces ?? new ChangeTrackingList(), - policyMode, - isBuiltInOnly, - resourceTypeAliases ?? new ChangeTrackingList(), - effects ?? new ChangeTrackingList(), - fieldValues ?? new ChangeTrackingList(), - standard ?? new ChangeTrackingList(), - custom ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.Append(" properties:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Namespaces), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" namespaces: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Namespaces)) - { - if (Namespaces.Any()) - { - builder.Append(" namespaces: "); - builder.AppendLine("["); - foreach (var item in Namespaces) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyMode), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyMode: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PolicyMode)) - { - builder.Append(" policyMode: "); - if (PolicyMode.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{PolicyMode}'''"); - } - else - { - builder.AppendLine($"'{PolicyMode}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(IsBuiltInOnly), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" isBuiltInOnly: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(IsBuiltInOnly)) - { - builder.Append(" isBuiltInOnly: "); - var boolValue = IsBuiltInOnly.Value == true ? "true" : "false"; - builder.AppendLine($"{boolValue}"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ResourceTypeAliases), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" resourceTypeAliases: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ResourceTypeAliases)) - { - if (ResourceTypeAliases.Any()) - { - builder.Append(" resourceTypeAliases: "); - builder.AppendLine("["); - foreach (var item in ResourceTypeAliases) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 6, true, " resourceTypeAliases: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Effects), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" effects: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Effects)) - { - if (Effects.Any()) - { - builder.Append(" effects: "); - builder.AppendLine("["); - foreach (var item in Effects) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 6, true, " effects: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(FieldValues), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" fieldValues: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(FieldValues)) - { - if (FieldValues.Any()) - { - builder.Append(" fieldValues: "); - builder.AppendLine("["); - foreach (var item in FieldValues) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - builder.Append(" resourceFunctions:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Standard), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" standard: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Standard)) - { - if (Standard.Any()) - { - builder.Append(" standard: "); - builder.AppendLine("["); - foreach (var item in Standard) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(CustomDefinitions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" custom: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(CustomDefinitions)) - { - if (CustomDefinitions.Any()) - { - builder.Append(" custom: "); - builder.AppendLine("["); - foreach (var item in CustomDefinitions) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 8, true, " custom: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine(" }"); - builder.AppendLine(" }"); - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(DataPolicyManifestData)} does not support writing '{options.Format}' format."); - } - } - - DataPolicyManifestData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeDataPolicyManifestData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DataPolicyManifestData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestData.cs deleted file mode 100644 index 32ace96c4d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestData.cs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the DataPolicyManifest data model. - /// The data policy manifest. - /// - public partial class DataPolicyManifestData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal DataPolicyManifestData() - { - Namespaces = new ChangeTrackingList(); - ResourceTypeAliases = new ChangeTrackingList(); - Effects = new ChangeTrackingList(); - FieldValues = new ChangeTrackingList(); - Standard = new ChangeTrackingList(); - CustomDefinitions = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The list of namespaces for the data policy manifest. - /// The policy mode of the data policy manifest. - /// A value indicating whether policy mode is allowed only in built-in definitions. - /// An array of resource type aliases. - /// The effect definition. - /// The non-alias field accessor values that can be used in the policy rule. - /// The standard resource functions (subscription and/or resourceGroup). - /// An array of data manifest custom resource definition. - /// Keeps track of any properties unknown to the library. - internal DataPolicyManifestData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, IReadOnlyList namespaces, string policyMode, bool? isBuiltInOnly, IReadOnlyList resourceTypeAliases, IReadOnlyList effects, IReadOnlyList fieldValues, IReadOnlyList standard, IReadOnlyList customDefinitions, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - Namespaces = namespaces; - PolicyMode = policyMode; - IsBuiltInOnly = isBuiltInOnly; - ResourceTypeAliases = resourceTypeAliases; - Effects = effects; - FieldValues = fieldValues; - Standard = standard; - CustomDefinitions = customDefinitions; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The list of namespaces for the data policy manifest. - [WirePath("properties.namespaces")] - public IReadOnlyList Namespaces { get; } - /// The policy mode of the data policy manifest. - [WirePath("properties.policyMode")] - public string PolicyMode { get; } - /// A value indicating whether policy mode is allowed only in built-in definitions. - [WirePath("properties.isBuiltInOnly")] - public bool? IsBuiltInOnly { get; } - /// An array of resource type aliases. - [WirePath("properties.resourceTypeAliases")] - public IReadOnlyList ResourceTypeAliases { get; } - /// The effect definition. - [WirePath("properties.effects")] - public IReadOnlyList Effects { get; } - /// The non-alias field accessor values that can be used in the policy rule. - [WirePath("properties.fieldValues")] - public IReadOnlyList FieldValues { get; } - /// The standard resource functions (subscription and/or resourceGroup). - [WirePath("properties.standard")] - public IReadOnlyList Standard { get; } - /// An array of data manifest custom resource definition. - [WirePath("properties.custom")] - public IReadOnlyList CustomDefinitions { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestResource.Serialization.cs deleted file mode 100644 index 6c713c5dfe..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class DataPolicyManifestResource : IJsonModel - { - private static DataPolicyManifestData s_dataDeserializationInstance; - private static DataPolicyManifestData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - DataPolicyManifestData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - DataPolicyManifestData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestResource.cs deleted file mode 100644 index 62e06308fa..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestResource.cs +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a DataPolicyManifest along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetDataPolicyManifestResource method. - /// Otherwise you can get one from its parent resource using the GetDataPolicyManifest method. - /// - public partial class DataPolicyManifestResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The policyMode. - public static ResourceIdentifier CreateResourceIdentifier(string policyMode) - { - var resourceId = $"/providers/Microsoft.Authorization/dataPolicyManifests/{policyMode}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _dataPolicyManifestClientDiagnostics; - private readonly DataPolicyManifestsRestOperations _dataPolicyManifestRestClient; - private readonly DataPolicyManifestData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Authorization/dataPolicyManifests"; - - /// Initializes a new instance of the class for mocking. - protected DataPolicyManifestResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal DataPolicyManifestResource(ArmClient client, DataPolicyManifestData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal DataPolicyManifestResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _dataPolicyManifestClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string dataPolicyManifestApiVersion); - _dataPolicyManifestRestClient = new DataPolicyManifestsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, dataPolicyManifestApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual DataPolicyManifestData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the data policy manifest with the given policy mode. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _dataPolicyManifestClientDiagnostics.CreateScope("DataPolicyManifestResource.Get"); - scope.Start(); - try - { - var response = await _dataPolicyManifestRestClient.GetByPolicyModeAsync(Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new DataPolicyManifestResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the data policy manifest with the given policy mode. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _dataPolicyManifestClientDiagnostics.CreateScope("DataPolicyManifestResource.Get"); - scope.Start(); - try - { - var response = _dataPolicyManifestRestClient.GetByPolicyMode(Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new DataPolicyManifestResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Extensions/ArmClient.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Extensions/ArmClient.cs deleted file mode 100644 index 611e8d348a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Extensions/ArmClient.cs +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using Azure.Core; -using Azure.ResourceManager.Resources; - -namespace Azure.ResourceManager -{ - public partial class ArmClient - { - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual PolicyAssignmentResource GetPolicyAssignmentResource(ResourceIdentifier id) - { - PolicyAssignmentResource.ValidateResourceId(id); - return new PolicyAssignmentResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual SubscriptionPolicyDefinitionResource GetSubscriptionPolicyDefinitionResource(ResourceIdentifier id) - { - SubscriptionPolicyDefinitionResource.ValidateResourceId(id); - return new SubscriptionPolicyDefinitionResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual TenantPolicyDefinitionResource GetTenantPolicyDefinitionResource(ResourceIdentifier id) - { - TenantPolicyDefinitionResource.ValidateResourceId(id); - return new TenantPolicyDefinitionResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual ManagementGroupPolicyDefinitionResource GetManagementGroupPolicyDefinitionResource(ResourceIdentifier id) - { - ManagementGroupPolicyDefinitionResource.ValidateResourceId(id); - return new ManagementGroupPolicyDefinitionResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual SubscriptionPolicySetDefinitionResource GetSubscriptionPolicySetDefinitionResource(ResourceIdentifier id) - { - SubscriptionPolicySetDefinitionResource.ValidateResourceId(id); - return new SubscriptionPolicySetDefinitionResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual TenantPolicySetDefinitionResource GetTenantPolicySetDefinitionResource(ResourceIdentifier id) - { - TenantPolicySetDefinitionResource.ValidateResourceId(id); - return new TenantPolicySetDefinitionResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual ManagementGroupPolicySetDefinitionResource GetManagementGroupPolicySetDefinitionResource(ResourceIdentifier id) - { - ManagementGroupPolicySetDefinitionResource.ValidateResourceId(id); - return new ManagementGroupPolicySetDefinitionResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual DataPolicyManifestResource GetDataPolicyManifestResource(ResourceIdentifier id) - { - DataPolicyManifestResource.ValidateResourceId(id); - return new DataPolicyManifestResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual ManagementLockResource GetManagementLockResource(ResourceIdentifier id) - { - ManagementLockResource.ValidateResourceId(id); - return new ManagementLockResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual ResourceProviderResource GetResourceProviderResource(ResourceIdentifier id) - { - ResourceProviderResource.ValidateResourceId(id); - return new ResourceProviderResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual ResourceGroupResource GetResourceGroupResource(ResourceIdentifier id) - { - ResourceGroupResource.ValidateResourceId(id); - return new ResourceGroupResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual TagResource GetTagResource(ResourceIdentifier id) - { - TagResource.ValidateResourceId(id); - return new TagResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual SubscriptionResource GetSubscriptionResource(ResourceIdentifier id) - { - SubscriptionResource.ValidateResourceId(id); - return new SubscriptionResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual FeatureResource GetFeatureResource(ResourceIdentifier id) - { - FeatureResource.ValidateResourceId(id); - return new FeatureResource(this, id); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Extensions/ArmResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Extensions/ArmResource.cs deleted file mode 100644 index a70590323b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Extensions/ArmResource.cs +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.ResourceManager.Resources; - -namespace Azure.ResourceManager -{ - public partial class ArmResource - { - /// Gets a collection of PolicyAssignmentResources in the ArmResource. - /// An object representing collection of PolicyAssignmentResources and their operations over a PolicyAssignmentResource. - public virtual PolicyAssignmentCollection GetPolicyAssignments() - { - return GetCachedClient(client => new PolicyAssignmentCollection(client, Id)); - } - - /// - /// This operation retrieves a single policy assignment, given its name and the scope it was created at. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetPolicyAssignmentAsync(string policyAssignmentName, CancellationToken cancellationToken = default) - { - return await GetPolicyAssignments().GetAsync(policyAssignmentName, cancellationToken).ConfigureAwait(false); - } - - /// - /// This operation retrieves a single policy assignment, given its name and the scope it was created at. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetPolicyAssignment(string policyAssignmentName, CancellationToken cancellationToken = default) - { - return GetPolicyAssignments().Get(policyAssignmentName, cancellationToken); - } - - /// Gets a collection of ManagementLockResources in the ArmResource. - /// An object representing collection of ManagementLockResources and their operations over a ManagementLockResource. - public virtual ManagementLockCollection GetManagementLocks() - { - return GetCachedClient(client => new ManagementLockCollection(client, Id)); - } - - /// - /// Get a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of lock. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetManagementLockAsync(string lockName, CancellationToken cancellationToken = default) - { - return await GetManagementLocks().GetAsync(lockName, cancellationToken).ConfigureAwait(false); - } - - /// - /// Get a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of lock. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetManagementLock(string lockName, CancellationToken cancellationToken = default) - { - return GetManagementLocks().Get(lockName, cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Extensions/ManagementGroupResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Extensions/ManagementGroupResource.cs deleted file mode 100644 index 2e6a3a5047..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Extensions/ManagementGroupResource.cs +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.ResourceManager.Resources; - -namespace Azure.ResourceManager.ManagementGroups -{ - public partial class ManagementGroupResource - { - /// Gets a collection of ManagementGroupPolicyDefinitionResources in the ManagementGroupResource. - /// An object representing collection of ManagementGroupPolicyDefinitionResources and their operations over a ManagementGroupPolicyDefinitionResource. - public virtual ManagementGroupPolicyDefinitionCollection GetManagementGroupPolicyDefinitions() - { - return GetCachedClient(client => new ManagementGroupPolicyDefinitionCollection(client, Id)); - } - - /// - /// This operation retrieves the policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetManagementGroupPolicyDefinitionAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - return await GetManagementGroupPolicyDefinitions().GetAsync(policyDefinitionName, cancellationToken).ConfigureAwait(false); - } - - /// - /// This operation retrieves the policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetManagementGroupPolicyDefinition(string policyDefinitionName, CancellationToken cancellationToken = default) - { - return GetManagementGroupPolicyDefinitions().Get(policyDefinitionName, cancellationToken); - } - - /// Gets a collection of ManagementGroupPolicySetDefinitionResources in the ManagementGroupResource. - /// An object representing collection of ManagementGroupPolicySetDefinitionResources and their operations over a ManagementGroupPolicySetDefinitionResource. - public virtual ManagementGroupPolicySetDefinitionCollection GetManagementGroupPolicySetDefinitions() - { - return GetCachedClient(client => new ManagementGroupPolicySetDefinitionCollection(client, Id)); - } - - /// - /// This operation retrieves the policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetManagementGroupPolicySetDefinitionAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - return await GetManagementGroupPolicySetDefinitions().GetAsync(policySetDefinitionName, cancellationToken).ConfigureAwait(false); - } - - /// - /// This operation retrieves the policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetManagementGroupPolicySetDefinition(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - return GetManagementGroupPolicySetDefinitions().Get(policySetDefinitionName, cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureCollection.cs deleted file mode 100644 index a0c55991a2..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureCollection.cs +++ /dev/null @@ -1,394 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetFeatures method from an instance of . - /// - public partial class FeatureCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _featureClientDiagnostics; - private readonly FeaturesRestOperations _featureRestClient; - - /// Initializes a new instance of the class for mocking. - protected FeatureCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal FeatureCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _featureClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", FeatureResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(FeatureResource.ResourceType, out string featureApiVersion); - _featureRestClient = new FeaturesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, featureApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceProviderResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceProviderResource.ResourceType), nameof(id)); - } - - /// - /// Gets the preview feature with the specified name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the feature to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var scope = _featureClientDiagnostics.CreateScope("FeatureCollection.Get"); - scope.Start(); - try - { - var response = await _featureRestClient.GetAsync(Id.SubscriptionId, Id.Provider, featureName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets the preview feature with the specified name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the feature to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var scope = _featureClientDiagnostics.CreateScope("FeatureCollection.Get"); - scope.Start(); - try - { - var response = _featureRestClient.Get(Id.SubscriptionId, Id.Provider, featureName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets all the preview features in a provider namespace that are available through AFEC for the subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features - /// - /// - /// Operation Id - /// Features_List - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _featureRestClient.CreateListRequest(Id.SubscriptionId, Id.Provider); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _featureRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, Id.Provider); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new FeatureResource(Client, FeatureData.DeserializeFeatureData(e)), _featureClientDiagnostics, Pipeline, "FeatureCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Gets all the preview features in a provider namespace that are available through AFEC for the subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features - /// - /// - /// Operation Id - /// Features_List - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _featureRestClient.CreateListRequest(Id.SubscriptionId, Id.Provider); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _featureRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, Id.Provider); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new FeatureResource(Client, FeatureData.DeserializeFeatureData(e)), _featureClientDiagnostics, Pipeline, "FeatureCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the feature to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var scope = _featureClientDiagnostics.CreateScope("FeatureCollection.Exists"); - scope.Start(); - try - { - var response = await _featureRestClient.GetAsync(Id.SubscriptionId, Id.Provider, featureName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the feature to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var scope = _featureClientDiagnostics.CreateScope("FeatureCollection.Exists"); - scope.Start(); - try - { - var response = _featureRestClient.Get(Id.SubscriptionId, Id.Provider, featureName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the feature to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var scope = _featureClientDiagnostics.CreateScope("FeatureCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _featureRestClient.GetAsync(Id.SubscriptionId, Id.Provider, featureName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the feature to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var scope = _featureClientDiagnostics.CreateScope("FeatureCollection.GetIfExists"); - scope.Start(); - try - { - var response = _featureRestClient.Get(Id.SubscriptionId, Id.Provider, featureName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureData.Serialization.cs deleted file mode 100644 index 6accda525b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureData.Serialization.cs +++ /dev/null @@ -1,244 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class FeatureData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(FeatureData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - if (Optional.IsDefined(Properties)) - { - writer.WritePropertyName("properties"u8); - writer.WriteObjectValue(Properties, options); - } - } - - FeatureData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(FeatureData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeFeatureData(document.RootElement, options); - } - - internal static FeatureData DeserializeFeatureData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - FeatureProperties properties = default; - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - properties = FeatureProperties.DeserializeFeatureProperties(property.Value, options); - continue; - } - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.SystemData); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new FeatureData( - id, - name, - type, - systemData, - properties, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue("FeatureState", out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" properties: "); - builder.AppendLine("{"); - builder.Append(" state: "); - builder.AppendLine(propertyOverride); - builder.AppendLine(" }"); - } - else - { - if (Optional.IsDefined(Properties)) - { - builder.Append(" properties: "); - BicepSerializationHelpers.AppendChildObject(builder, Properties, options, 2, false, " properties: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(FeatureData)} does not support writing '{options.Format}' format."); - } - } - - FeatureData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeFeatureData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(FeatureData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureData.cs deleted file mode 100644 index ef7d2ec42c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureData.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the Feature data model. - /// Previewed feature information. - /// - public partial class FeatureData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal FeatureData() - { - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// Properties of the previewed feature. - /// Keeps track of any properties unknown to the library. - internal FeatureData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, FeatureProperties properties, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - Properties = properties; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Properties of the previewed feature. - internal FeatureProperties Properties { get; } - /// The registration state of the feature for the subscription. - [WirePath("properties.state")] - public string FeatureState - { - get => Properties?.State; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureResource.Serialization.cs deleted file mode 100644 index 264d1675fc..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class FeatureResource : IJsonModel - { - private static FeatureData s_dataDeserializationInstance; - private static FeatureData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - FeatureData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - FeatureData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureResource.cs deleted file mode 100644 index 463ada11d3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/FeatureResource.cs +++ /dev/null @@ -1,316 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a Feature along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetFeatureResource method. - /// Otherwise you can get one from its parent resource using the GetFeature method. - /// - public partial class FeatureResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The subscriptionId. - /// The resourceProviderNamespace. - /// The featureName. - public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceProviderNamespace, string featureName) - { - var resourceId = $"/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _featureClientDiagnostics; - private readonly FeaturesRestOperations _featureRestClient; - private readonly FeatureData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Resources/features"; - - /// Initializes a new instance of the class for mocking. - protected FeatureResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal FeatureResource(ArmClient client, FeatureData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal FeatureResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _featureClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string featureApiVersion); - _featureRestClient = new FeaturesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, featureApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual FeatureData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - /// - /// Gets the preview feature with the specified name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _featureClientDiagnostics.CreateScope("FeatureResource.Get"); - scope.Start(); - try - { - var response = await _featureRestClient.GetAsync(Id.SubscriptionId, Id.ResourceType.Namespace, Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets the preview feature with the specified name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _featureClientDiagnostics.CreateScope("FeatureResource.Get"); - scope.Start(); - try - { - var response = _featureRestClient.Get(Id.SubscriptionId, Id.ResourceType.Namespace, Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Registers the preview feature for the subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/register - /// - /// - /// Operation Id - /// Features_Register - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> RegisterAsync(CancellationToken cancellationToken = default) - { - using var scope = _featureClientDiagnostics.CreateScope("FeatureResource.Register"); - scope.Start(); - try - { - var response = await _featureRestClient.RegisterAsync(Id.SubscriptionId, Id.ResourceType.Namespace, Id.Name, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Registers the preview feature for the subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/register - /// - /// - /// Operation Id - /// Features_Register - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Register(CancellationToken cancellationToken = default) - { - using var scope = _featureClientDiagnostics.CreateScope("FeatureResource.Register"); - scope.Start(); - try - { - var response = _featureRestClient.Register(Id.SubscriptionId, Id.ResourceType.Namespace, Id.Name, cancellationToken); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Unregisters the preview feature for the subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/unregister - /// - /// - /// Operation Id - /// Features_Unregister - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> UnregisterAsync(CancellationToken cancellationToken = default) - { - using var scope = _featureClientDiagnostics.CreateScope("FeatureResource.Unregister"); - scope.Start(); - try - { - var response = await _featureRestClient.UnregisterAsync(Id.SubscriptionId, Id.ResourceType.Namespace, Id.Name, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Unregisters the preview feature for the subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/unregister - /// - /// - /// Operation Id - /// Features_Unregister - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Unregister(CancellationToken cancellationToken = default) - { - using var scope = _featureClientDiagnostics.CreateScope("FeatureResource.Unregister"); - scope.Start(); - try - { - var response = _featureRestClient.Unregister(Id.SubscriptionId, Id.ResourceType.Namespace, Id.Name, cancellationToken); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/GenericResourceData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/GenericResourceData.Serialization.cs deleted file mode 100644 index 2dca8040b9..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/GenericResourceData.Serialization.cs +++ /dev/null @@ -1,609 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class GenericResourceData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(GenericResourceData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - if (Optional.IsDefined(Plan)) - { - writer.WritePropertyName("plan"u8); - JsonSerializer.Serialize(writer, Plan, ResourceManagerJsonContext.Default.ArmPlan); - } - if (Optional.IsDefined(Properties)) - { - writer.WritePropertyName("properties"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(Properties); -#else - using (JsonDocument document = JsonDocument.Parse(Properties, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - if (Optional.IsDefined(Kind)) - { - writer.WritePropertyName("kind"u8); - writer.WriteStringValue(Kind); - } - if (Optional.IsDefined(ManagedBy)) - { - writer.WritePropertyName("managedBy"u8); - writer.WriteStringValue(ManagedBy); - } - if (Optional.IsDefined(Sku)) - { - writer.WritePropertyName("sku"u8); - writer.WriteObjectValue(Sku, options); - } - if (Optional.IsDefined(Identity)) - { - writer.WritePropertyName("identity"u8); - JsonSerializer.Serialize(writer, Identity, ResourceManagerJsonContext.Default.ManagedServiceIdentity); - } - if (options.Format != "W" && Optional.IsDefined(CreatedOn)) - { - writer.WritePropertyName("createdTime"u8); - writer.WriteStringValue(CreatedOn.Value, "O"); - } - if (options.Format != "W" && Optional.IsDefined(ChangedOn)) - { - writer.WritePropertyName("changedTime"u8); - writer.WriteStringValue(ChangedOn.Value, "O"); - } - if (options.Format != "W" && Optional.IsDefined(ProvisioningState)) - { - writer.WritePropertyName("provisioningState"u8); - writer.WriteStringValue(ProvisioningState); - } - } - - GenericResourceData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(GenericResourceData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeGenericResourceData(document.RootElement, options); - } - - internal static GenericResourceData DeserializeGenericResourceData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ArmPlan plan = default; - BinaryData properties = default; - string kind = default; - string managedBy = default; - ResourcesSku sku = default; - ManagedServiceIdentity identity = default; - DateTimeOffset? createdTime = default; - DateTimeOffset? changedTime = default; - string provisioningState = default; - ExtendedLocation extendedLocation = default; - IDictionary tags = default; - AzureLocation location = default; - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("plan"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - plan = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.ArmPlan); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - properties = BinaryData.FromString(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("kind"u8)) - { - kind = property.Value.GetString(); - continue; - } - if (property.NameEquals("managedBy"u8)) - { - managedBy = property.Value.GetString(); - continue; - } - if (property.NameEquals("sku"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - sku = ResourcesSku.DeserializeResourcesSku(property.Value, options); - continue; - } - if (property.NameEquals("identity"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - identity = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.ManagedServiceIdentity); - continue; - } - if (property.NameEquals("createdTime"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - createdTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("changedTime"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - changedTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("provisioningState"u8)) - { - provisioningState = property.Value.GetString(); - continue; - } - if (property.NameEquals("extendedLocation"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - extendedLocation = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.ExtendedLocation); - continue; - } - if (property.NameEquals("tags"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - tags = dictionary; - continue; - } - if (property.NameEquals("location"u8)) - { - location = new AzureLocation(property.Value.GetString()); - continue; - } - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.SystemData); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new GenericResourceData( - id, - name, - type, - systemData, - tags ?? new ChangeTrackingDictionary(), - location, - extendedLocation, - serializedAdditionalRawData, - plan, - properties, - kind, - managedBy, - sku, - identity, - createdTime, - changedTime, - provisioningState); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Location), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" location: "); - builder.AppendLine(propertyOverride); - } - else - { - builder.Append(" location: "); - builder.AppendLine($"'{Location.ToString()}'"); - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Tags), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tags: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Tags)) - { - if (Tags.Any()) - { - builder.Append(" tags: "); - builder.AppendLine("{"); - foreach (var item in Tags) - { - builder.Append($" '{item.Key}': "); - if (item.Value == null) - { - builder.Append("null"); - continue; - } - if (item.Value.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{item.Value}'''"); - } - else - { - builder.AppendLine($"'{item.Value}'"); - } - } - builder.AppendLine(" }"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Plan), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" plan: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Plan)) - { - builder.Append(" plan: "); - BicepSerializationHelpers.AppendChildObject(builder, Plan, options, 2, false, " plan: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Properties), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" properties: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Properties)) - { - builder.Append(" properties: "); - builder.AppendLine($"'{Properties.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Kind), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" kind: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Kind)) - { - builder.Append(" kind: "); - if (Kind.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Kind}'''"); - } - else - { - builder.AppendLine($"'{Kind}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ManagedBy), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" managedBy: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ManagedBy)) - { - builder.Append(" managedBy: "); - if (ManagedBy.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ManagedBy}'''"); - } - else - { - builder.AppendLine($"'{ManagedBy}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Sku), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" sku: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Sku)) - { - builder.Append(" sku: "); - BicepSerializationHelpers.AppendChildObject(builder, Sku, options, 2, false, " sku: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Identity), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" identity: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Identity)) - { - builder.Append(" identity: "); - BicepSerializationHelpers.AppendChildObject(builder, Identity, options, 2, false, " identity: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(CreatedOn), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" createdTime: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(CreatedOn)) - { - builder.Append(" createdTime: "); - var formattedDateTimeString = TypeFormatters.ToString(CreatedOn.Value, "o"); - builder.AppendLine($"'{formattedDateTimeString}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ChangedOn), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" changedTime: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ChangedOn)) - { - builder.Append(" changedTime: "); - var formattedDateTimeString = TypeFormatters.ToString(ChangedOn.Value, "o"); - builder.AppendLine($"'{formattedDateTimeString}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ProvisioningState), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" provisioningState: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ProvisioningState)) - { - builder.Append(" provisioningState: "); - if (ProvisioningState.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ProvisioningState}'''"); - } - else - { - builder.AppendLine($"'{ProvisioningState}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ExtendedLocation), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" extendedLocation: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ExtendedLocation)) - { - builder.Append(" extendedLocation: "); - BicepSerializationHelpers.AppendChildObject(builder, ExtendedLocation, options, 2, false, " extendedLocation: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(GenericResourceData)} does not support writing '{options.Format}' format."); - } - } - - GenericResourceData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeGenericResourceData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(GenericResourceData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/GenericResourceData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/GenericResourceData.cs deleted file mode 100644 index 1440e3dc01..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/GenericResourceData.cs +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the GenericResource data model. - /// Resource information. - /// - public partial class GenericResourceData : TrackedResourceExtendedData - { - /// Initializes a new instance of . - /// The location. - public GenericResourceData(AzureLocation location) : base(location) - { - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The tags. - /// The location. - /// Resource extended location. - /// Keeps track of any properties unknown to the library. - /// The plan of the resource. - /// The resource properties. - /// The kind of the resource. - /// ID of the resource that manages this resource. - /// The SKU of the resource. - /// The identity of the resource. - /// The created time of the resource. This is only present if requested via the $expand query parameter. - /// The changed time of the resource. This is only present if requested via the $expand query parameter. - /// The provisioning state of the resource. This is only present if requested via the $expand query parameter. - internal GenericResourceData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, IDictionary tags, AzureLocation location, ExtendedLocation extendedLocation, IDictionary serializedAdditionalRawData, ArmPlan plan, BinaryData properties, string kind, string managedBy, ResourcesSku sku, ManagedServiceIdentity identity, DateTimeOffset? createdOn, DateTimeOffset? changedOn, string provisioningState) : base(id, name, resourceType, systemData, tags, location, extendedLocation, serializedAdditionalRawData) - { - Plan = plan; - Properties = properties; - Kind = kind; - ManagedBy = managedBy; - Sku = sku; - Identity = identity; - CreatedOn = createdOn; - ChangedOn = changedOn; - ProvisioningState = provisioningState; - } - - /// Initializes a new instance of for deserialization. - internal GenericResourceData() - { - } - - /// The plan of the resource. - [WirePath("plan")] - public ArmPlan Plan { get; set; } - /// - /// The resource properties. - /// - /// To assign an object to this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("properties")] - public BinaryData Properties { get; set; } - /// The kind of the resource. - [WirePath("kind")] - public string Kind { get; set; } - /// ID of the resource that manages this resource. - [WirePath("managedBy")] - public string ManagedBy { get; set; } - /// The SKU of the resource. - [WirePath("sku")] - public ResourcesSku Sku { get; set; } - /// The identity of the resource. - [WirePath("identity")] - public ManagedServiceIdentity Identity { get; set; } - /// The created time of the resource. This is only present if requested via the $expand query parameter. - [WirePath("createdTime")] - public DateTimeOffset? CreatedOn { get; } - /// The changed time of the resource. This is only present if requested via the $expand query parameter. - [WirePath("changedTime")] - public DateTimeOffset? ChangedOn { get; } - /// The provisioning state of the resource. This is only present if requested via the $expand query parameter. - [WirePath("provisioningState")] - public string ProvisioningState { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Internal/Utf8JsonRequestContent.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Internal/Utf8JsonRequestContent.cs deleted file mode 100644 index c0ffe14923..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Internal/Utf8JsonRequestContent.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.IO; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; - -namespace Azure.ResourceManager -{ - internal class Utf8JsonRequestContent : RequestContent - { - private readonly MemoryStream _stream; - private readonly RequestContent _content; - - public Utf8JsonRequestContent() - { - _stream = new MemoryStream(); - _content = Create(_stream); - JsonWriter = new Utf8JsonWriter(_stream); - } - - public Utf8JsonWriter JsonWriter { get; } - - public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default) - { - await JsonWriter.FlushAsync().ConfigureAwait(false); - await _content.WriteToAsync(stream, cancellationToken).ConfigureAwait(false); - } - - public override void WriteTo(Stream stream, CancellationToken cancellationToken = default) - { - JsonWriter.Flush(); - _content.WriteTo(stream, cancellationToken); - } - - public override bool TryComputeLength(out long length) - { - length = JsonWriter.BytesCommitted + JsonWriter.BytesPending; - return true; - } - - public override void Dispose() - { - JsonWriter.Dispose(); - _content.Dispose(); - _stream.Dispose(); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Internal/WirePathAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Internal/WirePathAttribute.cs deleted file mode 100644 index 4b7cb3247b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Internal/WirePathAttribute.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.Resources -{ - [AttributeUsage(AttributeTargets.Property)] - internal class WirePathAttribute : Attribute - { - private string _wirePath; - - public WirePathAttribute(string wirePath) - { - _wirePath = wirePath; - } - - public override string ToString() - { - return _wirePath; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/GenericResourceOperationSource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/GenericResourceOperationSource.cs deleted file mode 100644 index f8b70fafa0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/GenericResourceOperationSource.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.ClientModel.Primitives; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; - -namespace Azure.ResourceManager.Resources -{ - internal class GenericResourceOperationSource : IOperationSource - { - private readonly ArmClient _client; - - internal GenericResourceOperationSource(ArmClient client) - { - _client = client; - } - - GenericResource IOperationSource.CreateResult(Response response, CancellationToken cancellationToken) - { - var data = ModelReaderWriter.Read(response.Content, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default); - return new GenericResource(_client, data); - } - - async ValueTask IOperationSource.CreateResultAsync(Response response, CancellationToken cancellationToken) - { - var data = ModelReaderWriter.Read(response.Content, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default); - return await Task.FromResult(new GenericResource(_client, data)).ConfigureAwait(false); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourceGroupExportResultOperationSource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourceGroupExportResultOperationSource.cs deleted file mode 100644 index a2603f1e90..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourceGroupExportResultOperationSource.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal class ResourceGroupExportResultOperationSource : IOperationSource - { - ResourceGroupExportResult IOperationSource.CreateResult(Response response, CancellationToken cancellationToken) - { - using var document = JsonDocument.Parse(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - return ResourceGroupExportResult.DeserializeResourceGroupExportResult(document.RootElement); - } - - async ValueTask IOperationSource.CreateResultAsync(Response response, CancellationToken cancellationToken) - { - using var document = await JsonDocument.ParseAsync(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - return ResourceGroupExportResult.DeserializeResourceGroupExportResult(document.RootElement); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourcesArmOperation.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourcesArmOperation.cs deleted file mode 100644 index 92e96135b2..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourcesArmOperation.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ -#pragma warning disable SA1649 // File name should match first type name - internal class ResourcesArmOperation : ArmOperation -#pragma warning restore SA1649 // File name should match first type name - { - private readonly OperationInternal _operation; - private readonly RehydrationToken? _completeRehydrationToken; - private readonly NextLinkOperationImplementation _nextLinkOperation; - private readonly string _operationId; - - /// Initializes a new instance of ResourcesArmOperation for mocking. - protected ResourcesArmOperation() - { - } - - internal ResourcesArmOperation(Response response, RehydrationToken? rehydrationToken = null) - { - _operation = OperationInternal.Succeeded(response); - _completeRehydrationToken = rehydrationToken; - _operationId = GetOperationId(rehydrationToken); - } - - internal ResourcesArmOperation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response, OperationFinalStateVia finalStateVia, bool skipApiVersionOverride = false, string apiVersionOverrideValue = null) - { - var nextLinkOperation = NextLinkOperationImplementation.Create(pipeline, request.Method, request.Uri.ToUri(), response, finalStateVia, skipApiVersionOverride, apiVersionOverrideValue); - if (nextLinkOperation is NextLinkOperationImplementation nextLinkOperationValue) - { - _nextLinkOperation = nextLinkOperationValue; - _operationId = _nextLinkOperation.OperationId; - } - else - { - _completeRehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(request.Method, request.Uri.ToUri(), response, finalStateVia); - _operationId = GetOperationId(_completeRehydrationToken); - } - _operation = new OperationInternal(nextLinkOperation, clientDiagnostics, response, "ResourcesArmOperation", fallbackStrategy: new SequentialDelayStrategy()); - } - - private string GetOperationId(RehydrationToken? rehydrationToken) - { - if (rehydrationToken is null) - { - return null; - } - var lroDetails = ModelReaderWriter.Write(rehydrationToken, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default).ToObjectFromJson>(ResourceManagerJsonContext.Default.DictionaryStringString); - return lroDetails["id"]; - } - /// - public override string Id => _operationId ?? NextLinkOperationImplementation.NotSet; - - /// - public override RehydrationToken? GetRehydrationToken() => _nextLinkOperation?.GetRehydrationToken() ?? _completeRehydrationToken; - - /// - public override bool HasCompleted => _operation.HasCompleted; - - /// - public override Response GetRawResponse() => _operation.RawResponse; - - /// - public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); - - /// - public override ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); - - /// - public override Response WaitForCompletionResponse(CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponse(cancellationToken); - - /// - public override Response WaitForCompletionResponse(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponse(pollingInterval, cancellationToken); - - /// - public override ValueTask WaitForCompletionResponseAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponseAsync(cancellationToken); - - /// - public override ValueTask WaitForCompletionResponseAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponseAsync(pollingInterval, cancellationToken); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourcesArmOperationOfT.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourcesArmOperationOfT.cs deleted file mode 100644 index d9c3f6e3bc..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourcesArmOperationOfT.cs +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ -#pragma warning disable SA1649 // File name should match first type name - internal class ResourcesArmOperation : ArmOperation -#pragma warning restore SA1649 // File name should match first type name - { - private readonly OperationInternal _operation; - private readonly RehydrationToken? _completeRehydrationToken; - private readonly NextLinkOperationImplementation _nextLinkOperation; - private readonly string _operationId; - - /// Initializes a new instance of ResourcesArmOperation for mocking. - protected ResourcesArmOperation() - { - } - - internal ResourcesArmOperation(Response response, RehydrationToken? rehydrationToken = null) - { - _operation = OperationInternal.Succeeded(response.GetRawResponse(), response.Value); - _completeRehydrationToken = rehydrationToken; - _operationId = GetOperationId(rehydrationToken); - } - - internal ResourcesArmOperation(IOperationSource source, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response, OperationFinalStateVia finalStateVia, bool skipApiVersionOverride = false, string apiVersionOverrideValue = null) - { - var nextLinkOperation = NextLinkOperationImplementation.Create(pipeline, request.Method, request.Uri.ToUri(), response, finalStateVia, skipApiVersionOverride, apiVersionOverrideValue); - if (nextLinkOperation is NextLinkOperationImplementation nextLinkOperationValue) - { - _nextLinkOperation = nextLinkOperationValue; - _operationId = _nextLinkOperation.OperationId; - } - else - { - _completeRehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(request.Method, request.Uri.ToUri(), response, finalStateVia); - _operationId = GetOperationId(_completeRehydrationToken); - } - _operation = new OperationInternal(NextLinkOperationImplementation.Create(source, nextLinkOperation), clientDiagnostics, response, "ResourcesArmOperation", fallbackStrategy: new SequentialDelayStrategy()); - } - - private string GetOperationId(RehydrationToken? rehydrationToken) - { - if (rehydrationToken is null) - { - return null; - } - var lroDetails = ModelReaderWriter.Write( - rehydrationToken, - ModelReaderWriterOptions.Json, - AzureResourceManagerContext.Default).ToObjectFromJson>(ResourceManagerJsonContext.Default.DictionaryStringString); - return lroDetails["id"]; - } - /// - public override string Id => _operationId ?? NextLinkOperationImplementation.NotSet; - - /// - public override RehydrationToken? GetRehydrationToken() => _nextLinkOperation?.GetRehydrationToken() ?? _completeRehydrationToken; - - /// - public override T Value => _operation.Value; - - /// - public override bool HasValue => _operation.HasValue; - - /// - public override bool HasCompleted => _operation.HasCompleted; - - /// - public override Response GetRawResponse() => _operation.RawResponse; - - /// - public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); - - /// - public override ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); - - /// - public override Response WaitForCompletion(CancellationToken cancellationToken = default) => _operation.WaitForCompletion(cancellationToken); - - /// - public override Response WaitForCompletion(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletion(pollingInterval, cancellationToken); - - /// - public override ValueTask> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken); - - /// - public override ValueTask> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/TagResourceOperationSource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/TagResourceOperationSource.cs deleted file mode 100644 index 452c0702a4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/TagResourceOperationSource.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.ClientModel.Primitives; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; - -namespace Azure.ResourceManager.Resources -{ - internal class TagResourceOperationSource : IOperationSource - { - private readonly ArmClient _client; - - internal TagResourceOperationSource(ArmClient client) - { - _client = client; - } - - TagResource IOperationSource.CreateResult(Response response, CancellationToken cancellationToken) - { - var data = ModelReaderWriter.Read(response.Content, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default); - return new TagResource(_client, data); - } - - async ValueTask IOperationSource.CreateResultAsync(Response response, CancellationToken cancellationToken) - { - var data = ModelReaderWriter.Read(response.Content, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default); - return await Task.FromResult(new TagResource(_client, data)).ConfigureAwait(false); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionCollection.cs deleted file mode 100644 index a11c7b1d4d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionCollection.cs +++ /dev/null @@ -1,501 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetManagementGroupPolicyDefinitions method from an instance of . - /// - public partial class ManagementGroupPolicyDefinitionCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics; - private readonly PolicyDefinitionsRestOperations _managementGroupPolicyDefinitionPolicyDefinitionsRestClient; - - /// Initializes a new instance of the class for mocking. - protected ManagementGroupPolicyDefinitionCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal ManagementGroupPolicyDefinitionCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ManagementGroupPolicyDefinitionResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ManagementGroupPolicyDefinitionResource.ResourceType, out string managementGroupPolicyDefinitionPolicyDefinitionsApiVersion); - _managementGroupPolicyDefinitionPolicyDefinitionsRestClient = new PolicyDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementGroupPolicyDefinitionPolicyDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ManagementGroupResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ManagementGroupResource.ResourceType), nameof(id)); - } - - /// - /// This operation creates or updates a policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_CreateOrUpdateAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy definition to create. - /// The policy definition properties. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string policyDefinitionName, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateOrUpdateAtManagementGroupAsync(Id.Name, policyDefinitionName, data, cancellationToken).ConfigureAwait(false); - var uri = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateCreateOrUpdateAtManagementGroupRequestUri(Id.Name, policyDefinitionName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_CreateOrUpdateAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy definition to create. - /// The policy definition properties. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string policyDefinitionName, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateOrUpdateAtManagementGroup(Id.Name, policyDefinitionName, data, cancellationToken); - var uri = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateCreateOrUpdateAtManagementGroupRequestUri(Id.Name, policyDefinitionName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionCollection.Get"); - scope.Start(); - try - { - var response = await _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.GetAtManagementGroupAsync(Id.Name, policyDefinitionName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionCollection.Get"); - scope.Start(); - try - { - var response = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.GetAtManagementGroup(Id.Name, policyDefinitionName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a list of all the policy definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions - /// - /// - /// Operation Id - /// PolicyDefinitions_ListByManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateListByManagementGroupRequest(Id.Name, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateListByManagementGroupNextPageRequest(nextLink, Id.Name, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new ManagementGroupPolicyDefinitionResource(Client, PolicyDefinitionData.DeserializePolicyDefinitionData(e)), _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics, Pipeline, "ManagementGroupPolicyDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// This operation retrieves a list of all the policy definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions - /// - /// - /// Operation Id - /// PolicyDefinitions_ListByManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateListByManagementGroupRequest(Id.Name, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateListByManagementGroupNextPageRequest(nextLink, Id.Name, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new ManagementGroupPolicyDefinitionResource(Client, PolicyDefinitionData.DeserializePolicyDefinitionData(e)), _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics, Pipeline, "ManagementGroupPolicyDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = await _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.GetAtManagementGroupAsync(Id.Name, policyDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.GetAtManagementGroup(Id.Name, policyDefinitionName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.GetAtManagementGroupAsync(Id.Name, policyDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.GetAtManagementGroup(Id.Name, policyDefinitionName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionResource.Serialization.cs deleted file mode 100644 index 867c419838..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class ManagementGroupPolicyDefinitionResource : IJsonModel - { - private static PolicyDefinitionData s_dataDeserializationInstance; - private static PolicyDefinitionData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - PolicyDefinitionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - PolicyDefinitionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionResource.cs deleted file mode 100644 index f254f2ed5e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionResource.cs +++ /dev/null @@ -1,354 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a ManagementGroupPolicyDefinition along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetManagementGroupPolicyDefinitionResource method. - /// Otherwise you can get one from its parent resource using the GetManagementGroupPolicyDefinition method. - /// - public partial class ManagementGroupPolicyDefinitionResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The managementGroupId. - /// The policyDefinitionName. - public static ResourceIdentifier CreateResourceIdentifier(string managementGroupId, string policyDefinitionName) - { - var resourceId = $"/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics; - private readonly PolicyDefinitionsRestOperations _managementGroupPolicyDefinitionPolicyDefinitionsRestClient; - private readonly PolicyDefinitionData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Authorization/policyDefinitions"; - - /// Initializes a new instance of the class for mocking. - protected ManagementGroupPolicyDefinitionResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal ManagementGroupPolicyDefinitionResource(ArmClient client, PolicyDefinitionData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal ManagementGroupPolicyDefinitionResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string managementGroupPolicyDefinitionPolicyDefinitionsApiVersion); - _managementGroupPolicyDefinitionPolicyDefinitionsRestClient = new PolicyDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementGroupPolicyDefinitionPolicyDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual PolicyDefinitionData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionResource.Get"); - scope.Start(); - try - { - var response = await _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.GetAtManagementGroupAsync(Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionResource.Get"); - scope.Start(); - try - { - var response = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.GetAtManagementGroup(Id.Parent.Name, Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes the policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_DeleteAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual async Task DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionResource.Delete"); - scope.Start(); - try - { - var response = await _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.DeleteAtManagementGroupAsync(Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); - var uri = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateDeleteAtManagementGroupRequestUri(Id.Parent.Name, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes the policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_DeleteAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionResource.Delete"); - scope.Start(); - try - { - var response = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.DeleteAtManagementGroup(Id.Parent.Name, Id.Name, cancellationToken); - var uri = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateDeleteAtManagementGroupRequestUri(Id.Parent.Name, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_CreateOrUpdateAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The policy definition properties. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(WaitUntil waitUntil, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionResource.Update"); - scope.Start(); - try - { - var response = await _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateOrUpdateAtManagementGroupAsync(Id.Parent.Name, Id.Name, data, cancellationToken).ConfigureAwait(false); - var uri = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateCreateOrUpdateAtManagementGroupRequestUri(Id.Parent.Name, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_CreateOrUpdateAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The policy definition properties. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation Update(WaitUntil waitUntil, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionResource.Update"); - scope.Start(); - try - { - var response = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateOrUpdateAtManagementGroup(Id.Parent.Name, Id.Name, data, cancellationToken); - var uri = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateCreateOrUpdateAtManagementGroupRequestUri(Id.Parent.Name, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionCollection.cs deleted file mode 100644 index e556e58ffa..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionCollection.cs +++ /dev/null @@ -1,501 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetManagementGroupPolicySetDefinitions method from an instance of . - /// - public partial class ManagementGroupPolicySetDefinitionCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics; - private readonly PolicySetDefinitionsRestOperations _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient; - - /// Initializes a new instance of the class for mocking. - protected ManagementGroupPolicySetDefinitionCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal ManagementGroupPolicySetDefinitionCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ManagementGroupPolicySetDefinitionResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ManagementGroupPolicySetDefinitionResource.ResourceType, out string managementGroupPolicySetDefinitionPolicySetDefinitionsApiVersion); - _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient = new PolicySetDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementGroupPolicySetDefinitionPolicySetDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ManagementGroupResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ManagementGroupResource.ResourceType), nameof(id)); - } - - /// - /// This operation creates or updates a policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_CreateOrUpdateAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy set definition to create. - /// The policy set definition properties. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string policySetDefinitionName, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateOrUpdateAtManagementGroupAsync(Id.Name, policySetDefinitionName, data, cancellationToken).ConfigureAwait(false); - var uri = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateCreateOrUpdateAtManagementGroupRequestUri(Id.Name, policySetDefinitionName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_CreateOrUpdateAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy set definition to create. - /// The policy set definition properties. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string policySetDefinitionName, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateOrUpdateAtManagementGroup(Id.Name, policySetDefinitionName, data, cancellationToken); - var uri = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateCreateOrUpdateAtManagementGroupRequestUri(Id.Name, policySetDefinitionName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionCollection.Get"); - scope.Start(); - try - { - var response = await _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.GetAtManagementGroupAsync(Id.Name, policySetDefinitionName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionCollection.Get"); - scope.Start(); - try - { - var response = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.GetAtManagementGroup(Id.Name, policySetDefinitionName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a list of all the policy set definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions - /// - /// - /// Operation Id - /// PolicySetDefinitions_ListByManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListByManagementGroupRequest(Id.Name, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListByManagementGroupNextPageRequest(nextLink, Id.Name, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new ManagementGroupPolicySetDefinitionResource(Client, PolicySetDefinitionData.DeserializePolicySetDefinitionData(e)), _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics, Pipeline, "ManagementGroupPolicySetDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// This operation retrieves a list of all the policy set definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions - /// - /// - /// Operation Id - /// PolicySetDefinitions_ListByManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListByManagementGroupRequest(Id.Name, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListByManagementGroupNextPageRequest(nextLink, Id.Name, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new ManagementGroupPolicySetDefinitionResource(Client, PolicySetDefinitionData.DeserializePolicySetDefinitionData(e)), _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics, Pipeline, "ManagementGroupPolicySetDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = await _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.GetAtManagementGroupAsync(Id.Name, policySetDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.GetAtManagementGroup(Id.Name, policySetDefinitionName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.GetAtManagementGroupAsync(Id.Name, policySetDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.GetAtManagementGroup(Id.Name, policySetDefinitionName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionResource.Serialization.cs deleted file mode 100644 index 60c244d59e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class ManagementGroupPolicySetDefinitionResource : IJsonModel - { - private static PolicySetDefinitionData s_dataDeserializationInstance; - private static PolicySetDefinitionData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - PolicySetDefinitionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - PolicySetDefinitionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionResource.cs deleted file mode 100644 index 4f8ffed49d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionResource.cs +++ /dev/null @@ -1,354 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a ManagementGroupPolicySetDefinition along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetManagementGroupPolicySetDefinitionResource method. - /// Otherwise you can get one from its parent resource using the GetManagementGroupPolicySetDefinition method. - /// - public partial class ManagementGroupPolicySetDefinitionResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The managementGroupId. - /// The policySetDefinitionName. - public static ResourceIdentifier CreateResourceIdentifier(string managementGroupId, string policySetDefinitionName) - { - var resourceId = $"/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics; - private readonly PolicySetDefinitionsRestOperations _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient; - private readonly PolicySetDefinitionData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Authorization/policySetDefinitions"; - - /// Initializes a new instance of the class for mocking. - protected ManagementGroupPolicySetDefinitionResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal ManagementGroupPolicySetDefinitionResource(ArmClient client, PolicySetDefinitionData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal ManagementGroupPolicySetDefinitionResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string managementGroupPolicySetDefinitionPolicySetDefinitionsApiVersion); - _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient = new PolicySetDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementGroupPolicySetDefinitionPolicySetDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual PolicySetDefinitionData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionResource.Get"); - scope.Start(); - try - { - var response = await _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.GetAtManagementGroupAsync(Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionResource.Get"); - scope.Start(); - try - { - var response = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.GetAtManagementGroup(Id.Parent.Name, Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes the policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_DeleteAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual async Task DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionResource.Delete"); - scope.Start(); - try - { - var response = await _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.DeleteAtManagementGroupAsync(Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); - var uri = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateDeleteAtManagementGroupRequestUri(Id.Parent.Name, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes the policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_DeleteAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionResource.Delete"); - scope.Start(); - try - { - var response = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.DeleteAtManagementGroup(Id.Parent.Name, Id.Name, cancellationToken); - var uri = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateDeleteAtManagementGroupRequestUri(Id.Parent.Name, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_CreateOrUpdateAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The policy set definition properties. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(WaitUntil waitUntil, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionResource.Update"); - scope.Start(); - try - { - var response = await _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateOrUpdateAtManagementGroupAsync(Id.Parent.Name, Id.Name, data, cancellationToken).ConfigureAwait(false); - var uri = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateCreateOrUpdateAtManagementGroupRequestUri(Id.Parent.Name, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_CreateOrUpdateAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The policy set definition properties. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation Update(WaitUntil waitUntil, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionResource.Update"); - scope.Start(); - try - { - var response = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateOrUpdateAtManagementGroup(Id.Parent.Name, Id.Name, data, cancellationToken); - var uri = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateCreateOrUpdateAtManagementGroupRequestUri(Id.Parent.Name, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockCollection.cs deleted file mode 100644 index bb744b2095..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockCollection.cs +++ /dev/null @@ -1,488 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetManagementLocks method from an instance of . - /// - public partial class ManagementLockCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _managementLockClientDiagnostics; - private readonly ManagementLocksRestOperations _managementLockRestClient; - - /// Initializes a new instance of the class for mocking. - protected ManagementLockCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal ManagementLockCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementLockClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ManagementLockResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ManagementLockResource.ResourceType, out string managementLockApiVersion); - _managementLockRestClient = new ManagementLocksRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementLockApiVersion); - } - - /// - /// Create or update a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_CreateOrUpdateByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of lock. - /// Create or update management lock parameters. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string lockName, ManagementLockData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _managementLockRestClient.CreateOrUpdateByScopeAsync(Id, lockName, data, cancellationToken).ConfigureAwait(false); - var uri = _managementLockRestClient.CreateCreateOrUpdateByScopeRequestUri(Id, lockName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementLockResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Create or update a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_CreateOrUpdateByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of lock. - /// Create or update management lock parameters. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string lockName, ManagementLockData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = _managementLockRestClient.CreateOrUpdateByScope(Id, lockName, data, cancellationToken); - var uri = _managementLockRestClient.CreateCreateOrUpdateByScopeRequestUri(Id, lockName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementLockResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Get a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of lock. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockCollection.Get"); - scope.Start(); - try - { - var response = await _managementLockRestClient.GetByScopeAsync(Id, lockName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementLockResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Get a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of lock. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockCollection.Get"); - scope.Start(); - try - { - var response = _managementLockRestClient.GetByScope(Id, lockName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementLockResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets all the management locks for a scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks - /// - /// - /// Operation Id - /// ManagementLocks_ListByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementLockRestClient.CreateListByScopeRequest(Id, filter); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementLockRestClient.CreateListByScopeNextPageRequest(nextLink, Id, filter); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new ManagementLockResource(Client, ManagementLockData.DeserializeManagementLockData(e)), _managementLockClientDiagnostics, Pipeline, "ManagementLockCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Gets all the management locks for a scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks - /// - /// - /// Operation Id - /// ManagementLocks_ListByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementLockRestClient.CreateListByScopeRequest(Id, filter); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementLockRestClient.CreateListByScopeNextPageRequest(nextLink, Id, filter); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new ManagementLockResource(Client, ManagementLockData.DeserializeManagementLockData(e)), _managementLockClientDiagnostics, Pipeline, "ManagementLockCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of lock. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockCollection.Exists"); - scope.Start(); - try - { - var response = await _managementLockRestClient.GetByScopeAsync(Id, lockName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of lock. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockCollection.Exists"); - scope.Start(); - try - { - var response = _managementLockRestClient.GetByScope(Id, lockName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of lock. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _managementLockRestClient.GetByScopeAsync(Id, lockName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementLockResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of lock. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockCollection.GetIfExists"); - scope.Start(); - try - { - var response = _managementLockRestClient.GetByScope(Id, lockName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementLockResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockData.Serialization.cs deleted file mode 100644 index 3966a819f8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockData.Serialization.cs +++ /dev/null @@ -1,334 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class ManagementLockData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementLockData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - writer.WritePropertyName("level"u8); - writer.WriteStringValue(Level.ToString()); - if (Optional.IsDefined(Notes)) - { - writer.WritePropertyName("notes"u8); - writer.WriteStringValue(Notes); - } - if (Optional.IsCollectionDefined(Owners)) - { - writer.WritePropertyName("owners"u8); - writer.WriteStartArray(); - foreach (var item in Owners) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - writer.WriteEndObject(); - } - - ManagementLockData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementLockData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementLockData(document.RootElement, options); - } - - internal static ManagementLockData DeserializeManagementLockData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - ManagementLockLevel level = default; - string notes = default; - IList owners = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.SystemData); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("level"u8)) - { - level = new ManagementLockLevel(property0.Value.GetString()); - continue; - } - if (property0.NameEquals("notes"u8)) - { - notes = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("owners"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(ManagementLockOwner.DeserializeManagementLockOwner(item, options)); - } - owners = array; - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementLockData( - id, - name, - type, - systemData, - level, - notes, - owners ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.Append(" properties:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Level), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" level: "); - builder.AppendLine(propertyOverride); - } - else - { - builder.Append(" level: "); - builder.AppendLine($"'{Level.ToString()}'"); - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Notes), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" notes: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Notes)) - { - builder.Append(" notes: "); - if (Notes.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Notes}'''"); - } - else - { - builder.AppendLine($"'{Notes}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Owners), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" owners: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Owners)) - { - if (Owners.Any()) - { - builder.Append(" owners: "); - builder.AppendLine("["); - foreach (var item in Owners) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 6, true, " owners: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine(" }"); - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementLockData)} does not support writing '{options.Format}' format."); - } - } - - ManagementLockData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementLockData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementLockData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockData.cs deleted file mode 100644 index 64c9e5d2cd..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockData.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the ManagementLock data model. - /// The lock information. - /// - public partial class ManagementLockData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The level of the lock. Possible values are: NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users are able to read and modify the resources, but not delete. ReadOnly means authorized users can only read from a resource, but they can't modify or delete it. - public ManagementLockData(ManagementLockLevel level) - { - Level = level; - Owners = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The level of the lock. Possible values are: NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users are able to read and modify the resources, but not delete. ReadOnly means authorized users can only read from a resource, but they can't modify or delete it. - /// Notes about the lock. Maximum of 512 characters. - /// The owners of the lock. - /// Keeps track of any properties unknown to the library. - internal ManagementLockData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, ManagementLockLevel level, string notes, IList owners, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - Level = level; - Notes = notes; - Owners = owners; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal ManagementLockData() - { - } - - /// The level of the lock. Possible values are: NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users are able to read and modify the resources, but not delete. ReadOnly means authorized users can only read from a resource, but they can't modify or delete it. - [WirePath("properties.level")] - public ManagementLockLevel Level { get; set; } - /// Notes about the lock. Maximum of 512 characters. - [WirePath("properties.notes")] - public string Notes { get; set; } - /// The owners of the lock. - [WirePath("properties.owners")] - public IList Owners { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockResource.Serialization.cs deleted file mode 100644 index 3dfbf0b23b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class ManagementLockResource : IJsonModel - { - private static ManagementLockData s_dataDeserializationInstance; - private static ManagementLockData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - ManagementLockData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - ManagementLockData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockResource.cs deleted file mode 100644 index e02de890dd..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ManagementLockResource.cs +++ /dev/null @@ -1,353 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a ManagementLock along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetManagementLockResource method. - /// Otherwise you can get one from its parent resource using the GetManagementLock method. - /// - public partial class ManagementLockResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The scope. - /// The lockName. - public static ResourceIdentifier CreateResourceIdentifier(string scope, string lockName) - { - var resourceId = $"{scope}/providers/Microsoft.Authorization/locks/{lockName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _managementLockClientDiagnostics; - private readonly ManagementLocksRestOperations _managementLockRestClient; - private readonly ManagementLockData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Authorization/locks"; - - /// Initializes a new instance of the class for mocking. - protected ManagementLockResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal ManagementLockResource(ArmClient client, ManagementLockData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal ManagementLockResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementLockClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string managementLockApiVersion); - _managementLockRestClient = new ManagementLocksRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementLockApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual ManagementLockData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// Get a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockResource.Get"); - scope.Start(); - try - { - var response = await _managementLockRestClient.GetByScopeAsync(Id.Parent, Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementLockResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Get a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockResource.Get"); - scope.Start(); - try - { - var response = _managementLockRestClient.GetByScope(Id.Parent, Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementLockResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Delete a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_DeleteByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual async Task DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockResource.Delete"); - scope.Start(); - try - { - var response = await _managementLockRestClient.DeleteByScopeAsync(Id.Parent, Id.Name, cancellationToken).ConfigureAwait(false); - var uri = _managementLockRestClient.CreateDeleteByScopeRequestUri(Id.Parent, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Delete a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_DeleteByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockResource.Delete"); - scope.Start(); - try - { - var response = _managementLockRestClient.DeleteByScope(Id.Parent, Id.Name, cancellationToken); - var uri = _managementLockRestClient.CreateDeleteByScopeRequestUri(Id.Parent, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Create or update a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_CreateOrUpdateByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Create or update management lock parameters. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(WaitUntil waitUntil, ManagementLockData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockResource.Update"); - scope.Start(); - try - { - var response = await _managementLockRestClient.CreateOrUpdateByScopeAsync(Id.Parent, Id.Name, data, cancellationToken).ConfigureAwait(false); - var uri = _managementLockRestClient.CreateCreateOrUpdateByScopeRequestUri(Id.Parent, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementLockResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Create or update a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_CreateOrUpdateByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Create or update management lock parameters. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation Update(WaitUntil waitUntil, ManagementLockData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockResource.Update"); - scope.Start(); - try - { - var response = _managementLockRestClient.CreateOrUpdateByScope(Id.Parent, Id.Name, data, cancellationToken); - var uri = _managementLockRestClient.CreateCreateOrUpdateByScopeRequestUri(Id.Parent, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementLockResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ApiProfile.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ApiProfile.Serialization.cs deleted file mode 100644 index 0410aa5914..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ApiProfile.Serialization.cs +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ApiProfile : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ApiProfile)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(ProfileVersion)) - { - writer.WritePropertyName("profileVersion"u8); - writer.WriteStringValue(ProfileVersion); - } - if (options.Format != "W" && Optional.IsDefined(ApiVersion)) - { - writer.WritePropertyName("apiVersion"u8); - writer.WriteStringValue(ApiVersion); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ApiProfile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ApiProfile)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeApiProfile(document.RootElement, options); - } - - internal static ApiProfile DeserializeApiProfile(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string profileVersion = default; - string apiVersion = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("profileVersion"u8)) - { - profileVersion = property.Value.GetString(); - continue; - } - if (property.NameEquals("apiVersion"u8)) - { - apiVersion = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ApiProfile(profileVersion, apiVersion, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ProfileVersion), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" profileVersion: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ProfileVersion)) - { - builder.Append(" profileVersion: "); - if (ProfileVersion.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ProfileVersion}'''"); - } - else - { - builder.AppendLine($"'{ProfileVersion}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ApiVersion), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" apiVersion: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ApiVersion)) - { - builder.Append(" apiVersion: "); - if (ApiVersion.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ApiVersion}'''"); - } - else - { - builder.AppendLine($"'{ApiVersion}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ApiProfile)} does not support writing '{options.Format}' format."); - } - } - - ApiProfile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeApiProfile(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ApiProfile)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ApiProfile.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ApiProfile.cs deleted file mode 100644 index f739455520..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ApiProfile.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The ApiProfile. - public partial class ApiProfile - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ApiProfile() - { - } - - /// Initializes a new instance of . - /// The profile version. - /// The API version. - /// Keeps track of any properties unknown to the library. - internal ApiProfile(string profileVersion, string apiVersion, IDictionary serializedAdditionalRawData) - { - ProfileVersion = profileVersion; - ApiVersion = apiVersion; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The profile version. - [WirePath("profileVersion")] - public string ProfileVersion { get; } - /// The API version. - [WirePath("apiVersion")] - public string ApiVersion { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameter.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameter.Serialization.cs deleted file mode 100644 index 4c4698f06a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameter.Serialization.cs +++ /dev/null @@ -1,306 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ArmPolicyParameter : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmPolicyParameter)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(ParameterType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ParameterType.Value.ToString()); - } - if (Optional.IsCollectionDefined(AllowedValues)) - { - writer.WritePropertyName("allowedValues"u8); - writer.WriteStartArray(); - foreach (var item in AllowedValues) - { - if (item == null) - { - writer.WriteNullValue(); - continue; - } -#if NET6_0_OR_GREATER - writer.WriteRawValue(item); -#else - using (JsonDocument document = JsonDocument.Parse(item, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(DefaultValue)) - { - writer.WritePropertyName("defaultValue"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(DefaultValue); -#else - using (JsonDocument document = JsonDocument.Parse(DefaultValue, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - if (Optional.IsDefined(Metadata)) - { - writer.WritePropertyName("metadata"u8); - writer.WriteObjectValue(Metadata, options); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ArmPolicyParameter IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmPolicyParameter)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeArmPolicyParameter(document.RootElement, options); - } - - internal static ArmPolicyParameter DeserializeArmPolicyParameter(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ArmPolicyParameterType? type = default; - IList allowedValues = default; - BinaryData defaultValue = default; - ParameterDefinitionsValueMetadata metadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = new ArmPolicyParameterType(property.Value.GetString()); - continue; - } - if (property.NameEquals("allowedValues"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - if (item.ValueKind == JsonValueKind.Null) - { - array.Add(null); - } - else - { - array.Add(BinaryData.FromString(item.GetRawText())); - } - } - allowedValues = array; - continue; - } - if (property.NameEquals("defaultValue"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - defaultValue = BinaryData.FromString(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("metadata"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - metadata = ParameterDefinitionsValueMetadata.DeserializeParameterDefinitionsValueMetadata(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ArmPolicyParameter(type, allowedValues ?? new ChangeTrackingList(), defaultValue, metadata, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ParameterType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" type: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ParameterType)) - { - builder.Append(" type: "); - builder.AppendLine($"'{ParameterType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(AllowedValues), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" allowedValues: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(AllowedValues)) - { - if (AllowedValues.Any()) - { - builder.Append(" allowedValues: "); - builder.AppendLine("["); - foreach (var item in AllowedValues) - { - if (item == null) - { - builder.Append("null"); - continue; - } - builder.AppendLine($" '{item.ToString()}'"); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DefaultValue), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" defaultValue: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DefaultValue)) - { - builder.Append(" defaultValue: "); - builder.AppendLine($"'{DefaultValue.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Metadata), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" metadata: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Metadata)) - { - builder.Append(" metadata: "); - BicepSerializationHelpers.AppendChildObject(builder, Metadata, options, 2, false, " metadata: "); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ArmPolicyParameter)} does not support writing '{options.Format}' format."); - } - } - - ArmPolicyParameter IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeArmPolicyParameter(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ArmPolicyParameter)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameter.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameter.cs deleted file mode 100644 index 9eb8280256..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameter.cs +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The definition of a parameter that can be provided to the policy. - public partial class ArmPolicyParameter - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ArmPolicyParameter() - { - AllowedValues = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The data type of the parameter. - /// The allowed values for the parameter. - /// The default value for the parameter if no value is provided. - /// General metadata for the parameter. - /// Keeps track of any properties unknown to the library. - internal ArmPolicyParameter(ArmPolicyParameterType? parameterType, IList allowedValues, BinaryData defaultValue, ParameterDefinitionsValueMetadata metadata, IDictionary serializedAdditionalRawData) - { - ParameterType = parameterType; - AllowedValues = allowedValues; - DefaultValue = defaultValue; - Metadata = metadata; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The data type of the parameter. - [WirePath("type")] - public ArmPolicyParameterType? ParameterType { get; set; } - /// - /// The allowed values for the parameter. - /// - /// To assign an object to the element of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("allowedValues")] - public IList AllowedValues { get; } - /// - /// The default value for the parameter if no value is provided. - /// - /// To assign an object to this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("defaultValue")] - public BinaryData DefaultValue { get; set; } - /// General metadata for the parameter. - [WirePath("metadata")] - public ParameterDefinitionsValueMetadata Metadata { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterType.cs deleted file mode 100644 index c0dee9c68a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterType.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The data type of the parameter. - public readonly partial struct ArmPolicyParameterType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ArmPolicyParameterType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string StringValue = "String"; - private const string ArrayValue = "Array"; - private const string ObjectValue = "Object"; - private const string BooleanValue = "Boolean"; - private const string IntegerValue = "Integer"; - private const string FloatValue = "Float"; - private const string DateTimeValue = "DateTime"; - - /// String. - public static ArmPolicyParameterType String { get; } = new ArmPolicyParameterType(StringValue); - /// Array. - public static ArmPolicyParameterType Array { get; } = new ArmPolicyParameterType(ArrayValue); - /// Object. - public static ArmPolicyParameterType Object { get; } = new ArmPolicyParameterType(ObjectValue); - /// Boolean. - public static ArmPolicyParameterType Boolean { get; } = new ArmPolicyParameterType(BooleanValue); - /// Integer. - public static ArmPolicyParameterType Integer { get; } = new ArmPolicyParameterType(IntegerValue); - /// Float. - public static ArmPolicyParameterType Float { get; } = new ArmPolicyParameterType(FloatValue); - /// DateTime. - public static ArmPolicyParameterType DateTime { get; } = new ArmPolicyParameterType(DateTimeValue); - /// Determines if two values are the same. - public static bool operator ==(ArmPolicyParameterType left, ArmPolicyParameterType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ArmPolicyParameterType left, ArmPolicyParameterType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ArmPolicyParameterType(string value) => new ArmPolicyParameterType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ArmPolicyParameterType other && Equals(other); - /// - public bool Equals(ArmPolicyParameterType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterValue.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterValue.Serialization.cs deleted file mode 100644 index f2827a191a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterValue.Serialization.cs +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ArmPolicyParameterValue : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmPolicyParameterValue)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Value)) - { - writer.WritePropertyName("value"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(Value); -#else - using (JsonDocument document = JsonDocument.Parse(Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ArmPolicyParameterValue IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmPolicyParameterValue)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeArmPolicyParameterValue(document.RootElement, options); - } - - internal static ArmPolicyParameterValue DeserializeArmPolicyParameterValue(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - BinaryData value = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - value = BinaryData.FromString(property.Value.GetRawText()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ArmPolicyParameterValue(value, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Value)) - { - builder.Append(" value: "); - builder.AppendLine($"'{Value.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ArmPolicyParameterValue)} does not support writing '{options.Format}' format."); - } - } - - ArmPolicyParameterValue IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeArmPolicyParameterValue(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ArmPolicyParameterValue)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterValue.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterValue.cs deleted file mode 100644 index 0e055d7eb1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterValue.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The value of a parameter. - public partial class ArmPolicyParameterValue - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ArmPolicyParameterValue() - { - } - - /// Initializes a new instance of . - /// The value of the parameter. - /// Keeps track of any properties unknown to the library. - internal ArmPolicyParameterValue(BinaryData value, IDictionary serializedAdditionalRawData) - { - Value = value; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// - /// The value of the parameter. - /// - /// To assign an object to this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("value")] - public BinaryData Value { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/AvailabilityZoneMappings.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/AvailabilityZoneMappings.Serialization.cs deleted file mode 100644 index 098c56da1e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/AvailabilityZoneMappings.Serialization.cs +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class AvailabilityZoneMappings : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AvailabilityZoneMappings)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(LogicalZone)) - { - writer.WritePropertyName("logicalZone"u8); - writer.WriteStringValue(LogicalZone); - } - if (options.Format != "W" && Optional.IsDefined(PhysicalZone)) - { - writer.WritePropertyName("physicalZone"u8); - writer.WriteStringValue(PhysicalZone); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - AvailabilityZoneMappings IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AvailabilityZoneMappings)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAvailabilityZoneMappings(document.RootElement, options); - } - - internal static AvailabilityZoneMappings DeserializeAvailabilityZoneMappings(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string logicalZone = default; - string physicalZone = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("logicalZone"u8)) - { - logicalZone = property.Value.GetString(); - continue; - } - if (property.NameEquals("physicalZone"u8)) - { - physicalZone = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new AvailabilityZoneMappings(logicalZone, physicalZone, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(LogicalZone), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" logicalZone: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(LogicalZone)) - { - builder.Append(" logicalZone: "); - if (LogicalZone.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{LogicalZone}'''"); - } - else - { - builder.AppendLine($"'{LogicalZone}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PhysicalZone), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" physicalZone: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PhysicalZone)) - { - builder.Append(" physicalZone: "); - if (PhysicalZone.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{PhysicalZone}'''"); - } - else - { - builder.AppendLine($"'{PhysicalZone}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(AvailabilityZoneMappings)} does not support writing '{options.Format}' format."); - } - } - - AvailabilityZoneMappings IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeAvailabilityZoneMappings(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(AvailabilityZoneMappings)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/AvailabilityZoneMappings.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/AvailabilityZoneMappings.cs deleted file mode 100644 index 98f10092e5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/AvailabilityZoneMappings.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Availability zone mappings for the region. - public partial class AvailabilityZoneMappings - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal AvailabilityZoneMappings() - { - } - - /// Initializes a new instance of . - /// The logical zone id for the availability zone. - /// The fully qualified physical zone id of availability zone to which logical zone id is mapped to. - /// Keeps track of any properties unknown to the library. - internal AvailabilityZoneMappings(string logicalZone, string physicalZone, IDictionary serializedAdditionalRawData) - { - LogicalZone = logicalZone; - PhysicalZone = physicalZone; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The logical zone id for the availability zone. - [WirePath("logicalZone")] - public string LogicalZone { get; } - /// The fully qualified physical zone id of availability zone to which logical zone id is mapped to. - [WirePath("physicalZone")] - public string PhysicalZone { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/AzureRoleDefinition.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/AzureRoleDefinition.Serialization.cs deleted file mode 100644 index 15d4b4ed84..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/AzureRoleDefinition.Serialization.cs +++ /dev/null @@ -1,351 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class AzureRoleDefinition : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AzureRoleDefinition)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(IsServiceRole)) - { - writer.WritePropertyName("isServiceRole"u8); - writer.WriteBooleanValue(IsServiceRole.Value); - } - if (Optional.IsCollectionDefined(Permissions)) - { - writer.WritePropertyName("permissions"u8); - writer.WriteStartArray(); - foreach (var item in Permissions) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(Scopes)) - { - writer.WritePropertyName("scopes"u8); - writer.WriteStartArray(); - foreach (var item in Scopes) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - AzureRoleDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AzureRoleDefinition)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAzureRoleDefinition(document.RootElement, options); - } - - internal static AzureRoleDefinition DeserializeAzureRoleDefinition(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string id = default; - string name = default; - bool? isServiceRole = default; - IReadOnlyList permissions = default; - IReadOnlyList scopes = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("isServiceRole"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - isServiceRole = property.Value.GetBoolean(); - continue; - } - if (property.NameEquals("permissions"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(Permission.DeserializePermission(item, options)); - } - permissions = array; - continue; - } - if (property.NameEquals("scopes"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - scopes = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new AzureRoleDefinition( - id, - name, - isServiceRole, - permissions ?? new ChangeTrackingList(), - scopes ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - if (Id.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Id}'''"); - } - else - { - builder.AppendLine($"'{Id}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(IsServiceRole), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" isServiceRole: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(IsServiceRole)) - { - builder.Append(" isServiceRole: "); - var boolValue = IsServiceRole.Value == true ? "true" : "false"; - builder.AppendLine($"{boolValue}"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Permissions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" permissions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Permissions)) - { - if (Permissions.Any()) - { - builder.Append(" permissions: "); - builder.AppendLine("["); - foreach (var item in Permissions) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " permissions: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Scopes), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" scopes: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Scopes)) - { - if (Scopes.Any()) - { - builder.Append(" scopes: "); - builder.AppendLine("["); - foreach (var item in Scopes) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(AzureRoleDefinition)} does not support writing '{options.Format}' format."); - } - } - - AzureRoleDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeAzureRoleDefinition(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(AzureRoleDefinition)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/AzureRoleDefinition.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/AzureRoleDefinition.cs deleted file mode 100644 index f770872147..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/AzureRoleDefinition.cs +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Role definition properties. - public partial class AzureRoleDefinition - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal AzureRoleDefinition() - { - Permissions = new ChangeTrackingList(); - Scopes = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The role definition ID. - /// The role definition name. - /// If this is a service role. - /// Role definition permissions. - /// Role definition assignable scopes. - /// Keeps track of any properties unknown to the library. - internal AzureRoleDefinition(string id, string name, bool? isServiceRole, IReadOnlyList permissions, IReadOnlyList scopes, IDictionary serializedAdditionalRawData) - { - Id = id; - Name = name; - IsServiceRole = isServiceRole; - Permissions = permissions; - Scopes = scopes; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The role definition ID. - [WirePath("id")] - public string Id { get; } - /// The role definition name. - [WirePath("name")] - public string Name { get; } - /// If this is a service role. - [WirePath("isServiceRole")] - public bool? IsServiceRole { get; } - /// Role definition permissions. - [WirePath("permissions")] - public IReadOnlyList Permissions { get; } - /// Role definition assignable scopes. - [WirePath("scopes")] - public IReadOnlyList Scopes { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.Serialization.cs deleted file mode 100644 index 701b67d02c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.Serialization.cs +++ /dev/null @@ -1,293 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class DataManifestCustomResourceFunctionDefinition : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataManifestCustomResourceFunctionDefinition)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(FullyQualifiedResourceType)) - { - writer.WritePropertyName("fullyQualifiedResourceType"u8); - writer.WriteStringValue(FullyQualifiedResourceType.Value); - } - if (Optional.IsCollectionDefined(DefaultProperties)) - { - writer.WritePropertyName("defaultProperties"u8); - writer.WriteStartArray(); - foreach (var item in DefaultProperties) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(AllowCustomProperties)) - { - writer.WritePropertyName("allowCustomProperties"u8); - writer.WriteBooleanValue(AllowCustomProperties.Value); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - DataManifestCustomResourceFunctionDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataManifestCustomResourceFunctionDefinition)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDataManifestCustomResourceFunctionDefinition(document.RootElement, options); - } - - internal static DataManifestCustomResourceFunctionDefinition DeserializeDataManifestCustomResourceFunctionDefinition(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - ResourceType? fullyQualifiedResourceType = default; - IReadOnlyList defaultProperties = default; - bool? allowCustomProperties = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("fullyQualifiedResourceType"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - fullyQualifiedResourceType = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("defaultProperties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - defaultProperties = array; - continue; - } - if (property.NameEquals("allowCustomProperties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - allowCustomProperties = property.Value.GetBoolean(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new DataManifestCustomResourceFunctionDefinition(name, fullyQualifiedResourceType, defaultProperties ?? new ChangeTrackingList(), allowCustomProperties, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(FullyQualifiedResourceType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" fullyQualifiedResourceType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(FullyQualifiedResourceType)) - { - builder.Append(" fullyQualifiedResourceType: "); - builder.AppendLine($"'{FullyQualifiedResourceType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DefaultProperties), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" defaultProperties: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(DefaultProperties)) - { - if (DefaultProperties.Any()) - { - builder.Append(" defaultProperties: "); - builder.AppendLine("["); - foreach (var item in DefaultProperties) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(AllowCustomProperties), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" allowCustomProperties: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(AllowCustomProperties)) - { - builder.Append(" allowCustomProperties: "); - var boolValue = AllowCustomProperties.Value == true ? "true" : "false"; - builder.AppendLine($"{boolValue}"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(DataManifestCustomResourceFunctionDefinition)} does not support writing '{options.Format}' format."); - } - } - - DataManifestCustomResourceFunctionDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeDataManifestCustomResourceFunctionDefinition(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DataManifestCustomResourceFunctionDefinition)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.cs deleted file mode 100644 index 4f66f5b04c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.cs +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The custom resource function definition. - public partial class DataManifestCustomResourceFunctionDefinition - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal DataManifestCustomResourceFunctionDefinition() - { - DefaultProperties = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The function name as it will appear in the policy rule. eg - 'vault'. - /// The fully qualified control plane resource type that this function represents. eg - 'Microsoft.KeyVault/vaults'. - /// The top-level properties that can be selected on the function's output. eg - [ "name", "location" ] if vault().name and vault().location are supported. - /// A value indicating whether the custom properties within the property bag are allowed. Needs api-version to be specified in the policy rule eg - vault('2019-06-01'). - /// Keeps track of any properties unknown to the library. - internal DataManifestCustomResourceFunctionDefinition(string name, ResourceType? fullyQualifiedResourceType, IReadOnlyList defaultProperties, bool? allowCustomProperties, IDictionary serializedAdditionalRawData) - { - Name = name; - FullyQualifiedResourceType = fullyQualifiedResourceType; - DefaultProperties = defaultProperties; - AllowCustomProperties = allowCustomProperties; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The function name as it will appear in the policy rule. eg - 'vault'. - [WirePath("name")] - public string Name { get; } - /// The fully qualified control plane resource type that this function represents. eg - 'Microsoft.KeyVault/vaults'. - [WirePath("fullyQualifiedResourceType")] - public ResourceType? FullyQualifiedResourceType { get; } - /// The top-level properties that can be selected on the function's output. eg - [ "name", "location" ] if vault().name and vault().location are supported. - [WirePath("defaultProperties")] - public IReadOnlyList DefaultProperties { get; } - /// A value indicating whether the custom properties within the property bag are allowed. Needs api-version to be specified in the policy rule eg - vault('2019-06-01'). - [WirePath("allowCustomProperties")] - public bool? AllowCustomProperties { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestEffect.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestEffect.Serialization.cs deleted file mode 100644 index 7bee36daad..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestEffect.Serialization.cs +++ /dev/null @@ -1,207 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class DataPolicyManifestEffect : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataPolicyManifestEffect)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(DetailsSchema)) - { - writer.WritePropertyName("detailsSchema"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(DetailsSchema); -#else - using (JsonDocument document = JsonDocument.Parse(DetailsSchema, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - DataPolicyManifestEffect IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataPolicyManifestEffect)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDataPolicyManifestEffect(document.RootElement, options); - } - - internal static DataPolicyManifestEffect DeserializeDataPolicyManifestEffect(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - BinaryData detailsSchema = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("detailsSchema"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - detailsSchema = BinaryData.FromString(property.Value.GetRawText()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new DataPolicyManifestEffect(name, detailsSchema, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DetailsSchema), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" detailsSchema: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DetailsSchema)) - { - builder.Append(" detailsSchema: "); - builder.AppendLine($"'{DetailsSchema.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(DataPolicyManifestEffect)} does not support writing '{options.Format}' format."); - } - } - - DataPolicyManifestEffect IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeDataPolicyManifestEffect(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DataPolicyManifestEffect)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestEffect.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestEffect.cs deleted file mode 100644 index 140fcae664..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestEffect.cs +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The data effect definition. - public partial class DataPolicyManifestEffect - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal DataPolicyManifestEffect() - { - } - - /// Initializes a new instance of . - /// The data effect name. - /// The data effect details schema. - /// Keeps track of any properties unknown to the library. - internal DataPolicyManifestEffect(string name, BinaryData detailsSchema, IDictionary serializedAdditionalRawData) - { - Name = name; - DetailsSchema = detailsSchema; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The data effect name. - [WirePath("name")] - public string Name { get; } - /// - /// The data effect details schema. - /// - /// To assign an object to this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("detailsSchema")] - public BinaryData DetailsSchema { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestListResult.Serialization.cs deleted file mode 100644 index fb372a4e0a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class DataPolicyManifestListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataPolicyManifestListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - DataPolicyManifestListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataPolicyManifestListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDataPolicyManifestListResult(document.RootElement, options); - } - - internal static DataPolicyManifestListResult DeserializeDataPolicyManifestListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(DataPolicyManifestData.DeserializeDataPolicyManifestData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new DataPolicyManifestListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(DataPolicyManifestListResult)} does not support writing '{options.Format}' format."); - } - } - - DataPolicyManifestListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeDataPolicyManifestListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DataPolicyManifestListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestListResult.cs deleted file mode 100644 index 769a87638b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of data policy manifests. - internal partial class DataPolicyManifestListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal DataPolicyManifestListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of data policy manifests. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal DataPolicyManifestListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of data policy manifests. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/EnforcementMode.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/EnforcementMode.cs deleted file mode 100644 index 239bc9da67..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/EnforcementMode.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The policy assignment enforcement mode. Possible values are Default and DoNotEnforce. - public readonly partial struct EnforcementMode : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public EnforcementMode(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string DefaultValue = "Default"; - private const string DoNotEnforceValue = "DoNotEnforce"; - - /// The policy effect is enforced during resource creation or update. - public static EnforcementMode Default { get; } = new EnforcementMode(DefaultValue); - /// The policy effect is not enforced during resource creation or update. - public static EnforcementMode DoNotEnforce { get; } = new EnforcementMode(DoNotEnforceValue); - /// Determines if two values are the same. - public static bool operator ==(EnforcementMode left, EnforcementMode right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(EnforcementMode left, EnforcementMode right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator EnforcementMode(string value) => new EnforcementMode(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is EnforcementMode other && Equals(other); - /// - public bool Equals(EnforcementMode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExportTemplate.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExportTemplate.Serialization.cs deleted file mode 100644 index 491a31fce0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExportTemplate.Serialization.cs +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ExportTemplate : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ExportTemplate)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Resources)) - { - writer.WritePropertyName("resources"u8); - writer.WriteStartArray(); - foreach (var item in Resources) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(Options)) - { - writer.WritePropertyName("options"u8); - writer.WriteStringValue(Options); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ExportTemplate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ExportTemplate)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeExportTemplate(document.RootElement, options); - } - - internal static ExportTemplate DeserializeExportTemplate(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IList resources = default; - string options0 = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("resources"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - resources = array; - continue; - } - if (property.NameEquals("options"u8)) - { - options0 = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ExportTemplate(resources ?? new ChangeTrackingList(), options0, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ExportTemplate)} does not support writing '{options.Format}' format."); - } - } - - ExportTemplate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeExportTemplate(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ExportTemplate)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExportTemplate.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExportTemplate.cs deleted file mode 100644 index 43ce04a802..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExportTemplate.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Export resource group template request parameters. - public partial class ExportTemplate - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ExportTemplate() - { - Resources = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The IDs of the resources to filter the export by. To export all resources, supply an array with single entry '*'. - /// The export template options. A CSV-formatted list containing zero or more of the following: 'IncludeParameterDefaultValue', 'IncludeComments', 'SkipResourceNameParameterization', 'SkipAllParameterization'. - /// Keeps track of any properties unknown to the library. - internal ExportTemplate(IList resources, string options, IDictionary serializedAdditionalRawData) - { - Resources = resources; - Options = options; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The IDs of the resources to filter the export by. To export all resources, supply an array with single entry '*'. - [WirePath("resources")] - public IList Resources { get; } - /// The export template options. A CSV-formatted list containing zero or more of the following: 'IncludeParameterDefaultValue', 'IncludeComments', 'SkipResourceNameParameterization', 'SkipAllParameterization'. - [WirePath("options")] - public string Options { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocation.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocation.Serialization.cs deleted file mode 100644 index d3763ccf2d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocation.Serialization.cs +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - [JsonConverter(typeof(ExtendedLocationConverter))] - public partial class ExtendedLocation : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ExtendedLocation)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(ExtendedLocationType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ExtendedLocationType.Value.ToString()); - } - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - } - - ExtendedLocation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ExtendedLocation)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeExtendedLocation(document.RootElement, options); - } - - internal static ExtendedLocation DeserializeExtendedLocation(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ExtendedLocationType? type = default; - string name = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = new ExtendedLocationType(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - } - return new ExtendedLocation(type, name); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ExtendedLocationType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" type: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ExtendedLocationType)) - { - builder.Append(" type: "); - builder.AppendLine($"'{ExtendedLocationType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ExtendedLocation)} does not support writing '{options.Format}' format."); - } - } - - ExtendedLocation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeExtendedLocation(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ExtendedLocation)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class ExtendedLocationConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, ExtendedLocation model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model, ModelSerializationExtensions.WireOptions); - } - - public override ExtendedLocation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeExtendedLocation(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocation.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocation.cs deleted file mode 100644 index c052d4f1e8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocation.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Resource extended location. - [PropertyReferenceType] - public partial class ExtendedLocation - { - /// Initializes a new instance of . - [InitializationConstructor] - public ExtendedLocation() - { - } - - /// Initializes a new instance of . - /// The extended location type. - /// The extended location name. - [SerializationConstructor] - internal ExtendedLocation(ExtendedLocationType? extendedLocationType, string name) - { - ExtendedLocationType = extendedLocationType; - Name = name; - } - - /// The extended location type. - [WirePath("type")] - public ExtendedLocationType? ExtendedLocationType { get; set; } - /// The extended location name. - [WirePath("name")] - public string Name { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocationType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocationType.cs deleted file mode 100644 index 76cfe6ccdb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocationType.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The extended location type. - public readonly partial struct ExtendedLocationType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ExtendedLocationType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string EdgeZoneValue = "EdgeZone"; - - /// EdgeZone. - public static ExtendedLocationType EdgeZone { get; } = new ExtendedLocationType(EdgeZoneValue); - /// Determines if two values are the same. - public static bool operator ==(ExtendedLocationType left, ExtendedLocationType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ExtendedLocationType left, ExtendedLocationType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ExtendedLocationType(string value) => new ExtendedLocationType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ExtendedLocationType other && Equals(other); - /// - public bool Equals(ExtendedLocationType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/FeatureOperationsListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/FeatureOperationsListResult.Serialization.cs deleted file mode 100644 index 82ef256728..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/FeatureOperationsListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class FeatureOperationsListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(FeatureOperationsListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - FeatureOperationsListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(FeatureOperationsListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeFeatureOperationsListResult(document.RootElement, options); - } - - internal static FeatureOperationsListResult DeserializeFeatureOperationsListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(FeatureData.DeserializeFeatureData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new FeatureOperationsListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(FeatureOperationsListResult)} does not support writing '{options.Format}' format."); - } - } - - FeatureOperationsListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeFeatureOperationsListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(FeatureOperationsListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/FeatureOperationsListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/FeatureOperationsListResult.cs deleted file mode 100644 index e2063f4235..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/FeatureOperationsListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of previewed features. - internal partial class FeatureOperationsListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal FeatureOperationsListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The array of features. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal FeatureOperationsListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The array of features. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/FeatureProperties.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/FeatureProperties.Serialization.cs deleted file mode 100644 index 8ee5c29a9b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/FeatureProperties.Serialization.cs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class FeatureProperties : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(FeatureProperties)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(State)) - { - writer.WritePropertyName("state"u8); - writer.WriteStringValue(State); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - FeatureProperties IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(FeatureProperties)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeFeatureProperties(document.RootElement, options); - } - - internal static FeatureProperties DeserializeFeatureProperties(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string state = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("state"u8)) - { - state = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new FeatureProperties(state, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(State), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" state: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(State)) - { - builder.Append(" state: "); - if (State.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{State}'''"); - } - else - { - builder.AppendLine($"'{State}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(FeatureProperties)} does not support writing '{options.Format}' format."); - } - } - - FeatureProperties IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeFeatureProperties(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(FeatureProperties)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/FeatureProperties.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/FeatureProperties.cs deleted file mode 100644 index bab8758f08..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/FeatureProperties.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Information about feature. - internal partial class FeatureProperties - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal FeatureProperties() - { - } - - /// Initializes a new instance of . - /// The registration state of the feature for the subscription. - /// Keeps track of any properties unknown to the library. - internal FeatureProperties(string state, IDictionary serializedAdditionalRawData) - { - State = state; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The registration state of the feature for the subscription. - [WirePath("state")] - public string State { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationExpanded.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationExpanded.Serialization.cs deleted file mode 100644 index 9e24d82634..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationExpanded.Serialization.cs +++ /dev/null @@ -1,409 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class LocationExpanded : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(LocationExpanded)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && Optional.IsDefined(SubscriptionId)) - { - writer.WritePropertyName("subscriptionId"u8); - writer.WriteStringValue(SubscriptionId); - } - if (options.Format != "W" && Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (options.Format != "W" && Optional.IsDefined(LocationType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(LocationType.Value.ToSerialString()); - } - if (options.Format != "W" && Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (options.Format != "W" && Optional.IsDefined(RegionalDisplayName)) - { - writer.WritePropertyName("regionalDisplayName"u8); - writer.WriteStringValue(RegionalDisplayName); - } - if (Optional.IsDefined(Metadata)) - { - writer.WritePropertyName("metadata"u8); - writer.WriteObjectValue(Metadata, options); - } - if (Optional.IsCollectionDefined(AvailabilityZoneMappings)) - { - writer.WritePropertyName("availabilityZoneMappings"u8); - writer.WriteStartArray(); - foreach (var item in AvailabilityZoneMappings) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - LocationExpanded IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(LocationExpanded)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeLocationExpanded(document.RootElement, options); - } - - internal static LocationExpanded DeserializeLocationExpanded(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string id = default; - string subscriptionId = default; - string name = default; - LocationType? type = default; - string displayName = default; - string regionalDisplayName = default; - LocationMetadata metadata = default; - IReadOnlyList availabilityZoneMappings = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("subscriptionId"u8)) - { - subscriptionId = property.Value.GetString(); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = property.Value.GetString().ToLocationType(); - continue; - } - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (property.NameEquals("regionalDisplayName"u8)) - { - regionalDisplayName = property.Value.GetString(); - continue; - } - if (property.NameEquals("metadata"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - metadata = LocationMetadata.DeserializeLocationMetadata(property.Value, options); - continue; - } - if (property.NameEquals("availabilityZoneMappings"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(Models.AvailabilityZoneMappings.DeserializeAvailabilityZoneMappings(item, options)); - } - availabilityZoneMappings = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new LocationExpanded( - id, - subscriptionId, - name, - type, - displayName, - regionalDisplayName, - metadata, - availabilityZoneMappings ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - if (Id.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Id}'''"); - } - else - { - builder.AppendLine($"'{Id}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SubscriptionId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" subscriptionId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SubscriptionId)) - { - builder.Append(" subscriptionId: "); - if (SubscriptionId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{SubscriptionId}'''"); - } - else - { - builder.AppendLine($"'{SubscriptionId}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(RegionalDisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" regionalDisplayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(RegionalDisplayName)) - { - builder.Append(" regionalDisplayName: "); - if (RegionalDisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{RegionalDisplayName}'''"); - } - else - { - builder.AppendLine($"'{RegionalDisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Metadata), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" metadata: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Metadata)) - { - builder.Append(" metadata: "); - BicepSerializationHelpers.AppendChildObject(builder, Metadata, options, 2, false, " metadata: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(AvailabilityZoneMappings), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" availabilityZoneMappings: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(AvailabilityZoneMappings)) - { - if (AvailabilityZoneMappings.Any()) - { - builder.Append(" availabilityZoneMappings: "); - builder.AppendLine("["); - foreach (var item in AvailabilityZoneMappings) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " availabilityZoneMappings: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(LocationExpanded)} does not support writing '{options.Format}' format."); - } - } - - LocationExpanded IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLocationExpanded(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(LocationExpanded)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationExpanded.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationExpanded.cs deleted file mode 100644 index 60e4a76f90..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationExpanded.cs +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Location information. - public partial class LocationExpanded - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal LocationExpanded() - { - AvailabilityZoneMappings = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The fully qualified ID of the location. For example, /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74/locations/westus. - /// The subscription ID. - /// The location name. - /// The location type. - /// The display name of the location. - /// The display name of the location and its region. - /// Metadata of the location, such as lat/long, paired region, and others. - /// The availability zone mappings for this region. - /// Keeps track of any properties unknown to the library. - internal LocationExpanded(string id, string subscriptionId, string name, LocationType? locationType, string displayName, string regionalDisplayName, LocationMetadata metadata, IReadOnlyList availabilityZoneMappings, IDictionary serializedAdditionalRawData) - { - Id = id; - SubscriptionId = subscriptionId; - Name = name; - LocationType = locationType; - DisplayName = displayName; - RegionalDisplayName = regionalDisplayName; - Metadata = metadata; - AvailabilityZoneMappings = availabilityZoneMappings; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The fully qualified ID of the location. For example, /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74/locations/westus. - [WirePath("id")] - public string Id { get; } - /// The subscription ID. - [WirePath("subscriptionId")] - public string SubscriptionId { get; } - /// The location name. - [WirePath("name")] - public string Name { get; } - /// The location type. - [WirePath("type")] - public LocationType? LocationType { get; } - /// The display name of the location. - [WirePath("displayName")] - public string DisplayName { get; } - /// The display name of the location and its region. - [WirePath("regionalDisplayName")] - public string RegionalDisplayName { get; } - /// Metadata of the location, such as lat/long, paired region, and others. - [WirePath("metadata")] - public LocationMetadata Metadata { get; } - /// The availability zone mappings for this region. - [WirePath("availabilityZoneMappings")] - public IReadOnlyList AvailabilityZoneMappings { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationListResult.Serialization.cs deleted file mode 100644 index 570045b6f2..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationListResult.Serialization.cs +++ /dev/null @@ -1,185 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class LocationListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(LocationListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - LocationListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(LocationListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeLocationListResult(document.RootElement, options); - } - - internal static LocationListResult DeserializeLocationListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(LocationExpanded.DeserializeLocationExpanded(item, options)); - } - value = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new LocationListResult(value ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(LocationListResult)} does not support writing '{options.Format}' format."); - } - } - - LocationListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLocationListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(LocationListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationListResult.cs deleted file mode 100644 index a614638e72..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationListResult.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Location list operation response. - internal partial class LocationListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal LocationListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of locations. - /// Keeps track of any properties unknown to the library. - internal LocationListResult(IReadOnlyList value, IDictionary serializedAdditionalRawData) - { - Value = value; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of locations. - public IReadOnlyList Value { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationMetadata.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationMetadata.Serialization.cs deleted file mode 100644 index df28d93fb8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationMetadata.Serialization.cs +++ /dev/null @@ -1,443 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class LocationMetadata : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(LocationMetadata)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(RegionType)) - { - writer.WritePropertyName("regionType"u8); - writer.WriteStringValue(RegionType.Value.ToString()); - } - if (options.Format != "W" && Optional.IsDefined(RegionCategory)) - { - writer.WritePropertyName("regionCategory"u8); - writer.WriteStringValue(RegionCategory.Value.ToString()); - } - if (options.Format != "W" && Optional.IsDefined(Geography)) - { - writer.WritePropertyName("geography"u8); - writer.WriteStringValue(Geography); - } - if (options.Format != "W" && Optional.IsDefined(GeographyGroup)) - { - writer.WritePropertyName("geographyGroup"u8); - writer.WriteStringValue(GeographyGroup); - } - if (options.Format != "W" && Optional.IsDefined(Longitude)) - { - writer.WritePropertyName("longitude"u8); - WriteLongitude(writer, options); - } - if (options.Format != "W" && Optional.IsDefined(Latitude)) - { - writer.WritePropertyName("latitude"u8); - WriteLatitude(writer, options); - } - if (options.Format != "W" && Optional.IsDefined(PhysicalLocation)) - { - writer.WritePropertyName("physicalLocation"u8); - writer.WriteStringValue(PhysicalLocation); - } - if (Optional.IsCollectionDefined(PairedRegions)) - { - writer.WritePropertyName("pairedRegion"u8); - writer.WriteStartArray(); - foreach (var item in PairedRegions) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(HomeLocation)) - { - writer.WritePropertyName("homeLocation"u8); - writer.WriteStringValue(HomeLocation); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - LocationMetadata IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(LocationMetadata)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeLocationMetadata(document.RootElement, options); - } - - internal static LocationMetadata DeserializeLocationMetadata(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - RegionType? regionType = default; - RegionCategory? regionCategory = default; - string geography = default; - string geographyGroup = default; - double? longitude = default; - double? latitude = default; - string physicalLocation = default; - IReadOnlyList pairedRegion = default; - string homeLocation = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("regionType"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - regionType = new RegionType(property.Value.GetString()); - continue; - } - if (property.NameEquals("regionCategory"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - regionCategory = new RegionCategory(property.Value.GetString()); - continue; - } - if (property.NameEquals("geography"u8)) - { - geography = property.Value.GetString(); - continue; - } - if (property.NameEquals("geographyGroup"u8)) - { - geographyGroup = property.Value.GetString(); - continue; - } - if (property.NameEquals("longitude"u8)) - { - ReadLongitude(property, ref longitude); - continue; - } - if (property.NameEquals("latitude"u8)) - { - ReadLatitude(property, ref latitude); - continue; - } - if (property.NameEquals("physicalLocation"u8)) - { - physicalLocation = property.Value.GetString(); - continue; - } - if (property.NameEquals("pairedRegion"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(PairedRegion.DeserializePairedRegion(item, options)); - } - pairedRegion = array; - continue; - } - if (property.NameEquals("homeLocation"u8)) - { - homeLocation = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new LocationMetadata( - regionType, - regionCategory, - geography, - geographyGroup, - longitude, - latitude, - physicalLocation, - pairedRegion ?? new ChangeTrackingList(), - homeLocation, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(RegionType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" regionType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(RegionType)) - { - builder.Append(" regionType: "); - builder.AppendLine($"'{RegionType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(RegionCategory), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" regionCategory: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(RegionCategory)) - { - builder.Append(" regionCategory: "); - builder.AppendLine($"'{RegionCategory.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Geography), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" geography: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Geography)) - { - builder.Append(" geography: "); - if (Geography.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Geography}'''"); - } - else - { - builder.AppendLine($"'{Geography}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(GeographyGroup), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" geographyGroup: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(GeographyGroup)) - { - builder.Append(" geographyGroup: "); - if (GeographyGroup.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{GeographyGroup}'''"); - } - else - { - builder.AppendLine($"'{GeographyGroup}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Longitude), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" longitude: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Longitude)) - { - builder.Append(" longitude: "); - builder.AppendLine($"'{Longitude.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Latitude), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" latitude: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Latitude)) - { - builder.Append(" latitude: "); - builder.AppendLine($"'{Latitude.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PhysicalLocation), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" physicalLocation: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PhysicalLocation)) - { - builder.Append(" physicalLocation: "); - if (PhysicalLocation.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{PhysicalLocation}'''"); - } - else - { - builder.AppendLine($"'{PhysicalLocation}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PairedRegions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" pairedRegion: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(PairedRegions)) - { - if (PairedRegions.Any()) - { - builder.Append(" pairedRegion: "); - builder.AppendLine("["); - foreach (var item in PairedRegions) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " pairedRegion: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(HomeLocation), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" homeLocation: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(HomeLocation)) - { - builder.Append(" homeLocation: "); - if (HomeLocation.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{HomeLocation}'''"); - } - else - { - builder.AppendLine($"'{HomeLocation}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(LocationMetadata)} does not support writing '{options.Format}' format."); - } - } - - LocationMetadata IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLocationMetadata(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(LocationMetadata)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationMetadata.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationMetadata.cs deleted file mode 100644 index 4fe985db7d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationMetadata.cs +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Location metadata information. - public partial class LocationMetadata - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal LocationMetadata() - { - PairedRegions = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The type of the region. - /// The category of the region. - /// The geography of the location. - /// The geography group of the location. - /// The longitude of the location. - /// The latitude of the location. - /// The physical location of the Azure location. - /// The regions paired to this region. - /// The home location of an edge zone. - /// Keeps track of any properties unknown to the library. - internal LocationMetadata(RegionType? regionType, RegionCategory? regionCategory, string geography, string geographyGroup, double? longitude, double? latitude, string physicalLocation, IReadOnlyList pairedRegions, string homeLocation, IDictionary serializedAdditionalRawData) - { - RegionType = regionType; - RegionCategory = regionCategory; - Geography = geography; - GeographyGroup = geographyGroup; - Longitude = longitude; - Latitude = latitude; - PhysicalLocation = physicalLocation; - PairedRegions = pairedRegions; - HomeLocation = homeLocation; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The type of the region. - [WirePath("regionType")] - public RegionType? RegionType { get; } - /// The category of the region. - [WirePath("regionCategory")] - public RegionCategory? RegionCategory { get; } - /// The geography of the location. - [WirePath("geography")] - public string Geography { get; } - /// The geography group of the location. - [WirePath("geographyGroup")] - public string GeographyGroup { get; } - /// The physical location of the Azure location. - [WirePath("physicalLocation")] - public string PhysicalLocation { get; } - /// The regions paired to this region. - [WirePath("pairedRegion")] - public IReadOnlyList PairedRegions { get; } - /// The home location of an edge zone. - [WirePath("homeLocation")] - public string HomeLocation { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationType.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationType.Serialization.cs deleted file mode 100644 index 95769ed54d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationType.Serialization.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.Resources.Models -{ - internal static partial class LocationTypeExtensions - { - public static string ToSerialString(this LocationType value) => value switch - { - LocationType.Region => "Region", - LocationType.EdgeZone => "EdgeZone", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown LocationType value.") - }; - - public static LocationType ToLocationType(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Region")) return LocationType.Region; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "EdgeZone")) return LocationType.EdgeZone; - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown LocationType value."); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationType.cs deleted file mode 100644 index fe985afe37..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/LocationType.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.Resources.Models -{ - /// The location type. - public enum LocationType - { - /// Region. - Region, - /// EdgeZone. - EdgeZone - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagedByTenant.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagedByTenant.Serialization.cs deleted file mode 100644 index 7e0477da19..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagedByTenant.Serialization.cs +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ManagedByTenant : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagedByTenant)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(TenantId)) - { - writer.WritePropertyName("tenantId"u8); - writer.WriteStringValue(TenantId.Value); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ManagedByTenant IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagedByTenant)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagedByTenant(document.RootElement, options); - } - - internal static ManagedByTenant DeserializeManagedByTenant(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - Guid? tenantId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("tenantId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - tenantId = property.Value.GetGuid(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagedByTenant(tenantId, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TenantId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenantId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TenantId)) - { - builder.Append(" tenantId: "); - builder.AppendLine($"'{TenantId.Value.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagedByTenant)} does not support writing '{options.Format}' format."); - } - } - - ManagedByTenant IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagedByTenant(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagedByTenant)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagedByTenant.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagedByTenant.cs deleted file mode 100644 index 17afaec3ad..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagedByTenant.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Information about a tenant managing the subscription. - public partial class ManagedByTenant - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagedByTenant() - { - } - - /// Initializes a new instance of . - /// The tenant ID of the managing tenant. This is a GUID. - /// Keeps track of any properties unknown to the library. - internal ManagedByTenant(Guid? tenantId, IDictionary serializedAdditionalRawData) - { - TenantId = tenantId; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The tenant ID of the managing tenant. This is a GUID. - [WirePath("tenantId")] - public Guid? TenantId { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockLevel.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockLevel.cs deleted file mode 100644 index f3f6fa4cf8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockLevel.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The level of the lock. Possible values are: NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users are able to read and modify the resources, but not delete. ReadOnly means authorized users can only read from a resource, but they can't modify or delete it. - public readonly partial struct ManagementLockLevel : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ManagementLockLevel(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string NotSpecifiedValue = "NotSpecified"; - private const string CanNotDeleteValue = "CanNotDelete"; - private const string ReadOnlyValue = "ReadOnly"; - - /// NotSpecified. - public static ManagementLockLevel NotSpecified { get; } = new ManagementLockLevel(NotSpecifiedValue); - /// CanNotDelete. - public static ManagementLockLevel CanNotDelete { get; } = new ManagementLockLevel(CanNotDeleteValue); - /// ReadOnly. - public static ManagementLockLevel ReadOnly { get; } = new ManagementLockLevel(ReadOnlyValue); - /// Determines if two values are the same. - public static bool operator ==(ManagementLockLevel left, ManagementLockLevel right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ManagementLockLevel left, ManagementLockLevel right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ManagementLockLevel(string value) => new ManagementLockLevel(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ManagementLockLevel other && Equals(other); - /// - public bool Equals(ManagementLockLevel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockListResult.Serialization.cs deleted file mode 100644 index 5bb5c7ed46..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class ManagementLockListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementLockListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ManagementLockListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementLockListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementLockListResult(document.RootElement, options); - } - - internal static ManagementLockListResult DeserializeManagementLockListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ManagementLockData.DeserializeManagementLockData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementLockListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementLockListResult)} does not support writing '{options.Format}' format."); - } - } - - ManagementLockListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementLockListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementLockListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockListResult.cs deleted file mode 100644 index 7702747e45..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The list of locks. - internal partial class ManagementLockListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagementLockListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The list of locks. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal ManagementLockListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The list of locks. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockOwner.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockOwner.Serialization.cs deleted file mode 100644 index aa2bec2bd9..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockOwner.Serialization.cs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ManagementLockOwner : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementLockOwner)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(ApplicationId)) - { - writer.WritePropertyName("applicationId"u8); - writer.WriteStringValue(ApplicationId); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ManagementLockOwner IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementLockOwner)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementLockOwner(document.RootElement, options); - } - - internal static ManagementLockOwner DeserializeManagementLockOwner(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string applicationId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("applicationId"u8)) - { - applicationId = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementLockOwner(applicationId, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ApplicationId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" applicationId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ApplicationId)) - { - builder.Append(" applicationId: "); - if (ApplicationId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ApplicationId}'''"); - } - else - { - builder.AppendLine($"'{ApplicationId}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementLockOwner)} does not support writing '{options.Format}' format."); - } - } - - ManagementLockOwner IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementLockOwner(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementLockOwner)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockOwner.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockOwner.cs deleted file mode 100644 index 7cb1045193..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockOwner.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Lock owner properties. - public partial class ManagementLockOwner - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ManagementLockOwner() - { - } - - /// Initializes a new instance of . - /// The application ID of the lock owner. - /// Keeps track of any properties unknown to the library. - internal ManagementLockOwner(string applicationId, IDictionary serializedAdditionalRawData) - { - ApplicationId = applicationId; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The application ID of the lock owner. - [WirePath("applicationId")] - public string ApplicationId { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/NonComplianceMessage.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/NonComplianceMessage.Serialization.cs deleted file mode 100644 index 92a04db6d4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/NonComplianceMessage.Serialization.cs +++ /dev/null @@ -1,201 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class NonComplianceMessage : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(NonComplianceMessage)} does not support writing '{format}' format."); - } - - writer.WritePropertyName("message"u8); - writer.WriteStringValue(Message); - if (Optional.IsDefined(PolicyDefinitionReferenceId)) - { - writer.WritePropertyName("policyDefinitionReferenceId"u8); - writer.WriteStringValue(PolicyDefinitionReferenceId); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - NonComplianceMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(NonComplianceMessage)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeNonComplianceMessage(document.RootElement, options); - } - - internal static NonComplianceMessage DeserializeNonComplianceMessage(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string message = default; - string policyDefinitionReferenceId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("message"u8)) - { - message = property.Value.GetString(); - continue; - } - if (property.NameEquals("policyDefinitionReferenceId"u8)) - { - policyDefinitionReferenceId = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new NonComplianceMessage(message, policyDefinitionReferenceId, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Message), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" message: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Message)) - { - builder.Append(" message: "); - if (Message.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Message}'''"); - } - else - { - builder.AppendLine($"'{Message}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyDefinitionReferenceId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyDefinitionReferenceId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PolicyDefinitionReferenceId)) - { - builder.Append(" policyDefinitionReferenceId: "); - if (PolicyDefinitionReferenceId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{PolicyDefinitionReferenceId}'''"); - } - else - { - builder.AppendLine($"'{PolicyDefinitionReferenceId}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(NonComplianceMessage)} does not support writing '{options.Format}' format."); - } - } - - NonComplianceMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeNonComplianceMessage(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(NonComplianceMessage)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/NonComplianceMessage.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/NonComplianceMessage.cs deleted file mode 100644 index a412852eaa..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/NonComplianceMessage.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// A message that describes why a resource is non-compliant with the policy. This is shown in 'deny' error messages and on resource's non-compliant compliance results. - public partial class NonComplianceMessage - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// A message that describes why a resource is non-compliant with the policy. This is shown in 'deny' error messages and on resource's non-compliant compliance results. - /// is null. - public NonComplianceMessage(string message) - { - Argument.AssertNotNull(message, nameof(message)); - - Message = message; - } - - /// Initializes a new instance of . - /// A message that describes why a resource is non-compliant with the policy. This is shown in 'deny' error messages and on resource's non-compliant compliance results. - /// The policy definition reference ID within a policy set definition the message is intended for. This is only applicable if the policy assignment assigns a policy set definition. If this is not provided the message applies to all policies assigned by this policy assignment. - /// Keeps track of any properties unknown to the library. - internal NonComplianceMessage(string message, string policyDefinitionReferenceId, IDictionary serializedAdditionalRawData) - { - Message = message; - PolicyDefinitionReferenceId = policyDefinitionReferenceId; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal NonComplianceMessage() - { - } - - /// A message that describes why a resource is non-compliant with the policy. This is shown in 'deny' error messages and on resource's non-compliant compliance results. - [WirePath("message")] - public string Message { get; set; } - /// The policy definition reference ID within a policy set definition the message is intended for. This is only applicable if the policy assignment assigns a policy set definition. If this is not provided the message applies to all policies assigned by this policy assignment. - [WirePath("policyDefinitionReferenceId")] - public string PolicyDefinitionReferenceId { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PairedRegion.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PairedRegion.Serialization.cs deleted file mode 100644 index 5e20e69ed5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PairedRegion.Serialization.cs +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class PairedRegion : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PairedRegion)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && Optional.IsDefined(SubscriptionId)) - { - writer.WritePropertyName("subscriptionId"u8); - writer.WriteStringValue(SubscriptionId); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - PairedRegion IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PairedRegion)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePairedRegion(document.RootElement, options); - } - - internal static PairedRegion DeserializePairedRegion(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - string id = default; - string subscriptionId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("subscriptionId"u8)) - { - subscriptionId = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PairedRegion(name, id, subscriptionId, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - if (Id.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Id}'''"); - } - else - { - builder.AppendLine($"'{Id}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SubscriptionId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" subscriptionId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SubscriptionId)) - { - builder.Append(" subscriptionId: "); - if (SubscriptionId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{SubscriptionId}'''"); - } - else - { - builder.AppendLine($"'{SubscriptionId}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PairedRegion)} does not support writing '{options.Format}' format."); - } - } - - PairedRegion IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePairedRegion(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PairedRegion)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PairedRegion.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PairedRegion.cs deleted file mode 100644 index b4e30a1a8f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PairedRegion.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Information regarding paired region. - public partial class PairedRegion - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal PairedRegion() - { - } - - /// Initializes a new instance of . - /// The name of the paired region. - /// The fully qualified ID of the location. For example, /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74/locations/westus. - /// The subscription ID. - /// Keeps track of any properties unknown to the library. - internal PairedRegion(string name, string id, string subscriptionId, IDictionary serializedAdditionalRawData) - { - Name = name; - Id = id; - SubscriptionId = subscriptionId; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The name of the paired region. - [WirePath("name")] - public string Name { get; } - /// The fully qualified ID of the location. For example, /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74/locations/westus. - [WirePath("id")] - public string Id { get; } - /// The subscription ID. - [WirePath("subscriptionId")] - public string SubscriptionId { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ParameterDefinitionsValueMetadata.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ParameterDefinitionsValueMetadata.Serialization.cs deleted file mode 100644 index f90e74ef9a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ParameterDefinitionsValueMetadata.Serialization.cs +++ /dev/null @@ -1,263 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ParameterDefinitionsValueMetadata : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ParameterDefinitionsValueMetadata)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (Optional.IsDefined(Description)) - { - writer.WritePropertyName("description"u8); - writer.WriteStringValue(Description); - } - if (Optional.IsDefined(StrongType)) - { - writer.WritePropertyName("strongType"u8); - writer.WriteStringValue(StrongType); - } - if (Optional.IsDefined(AssignPermissions)) - { - writer.WritePropertyName("assignPermissions"u8); - writer.WriteBooleanValue(AssignPermissions.Value); - } - foreach (var item in AdditionalProperties) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - - ParameterDefinitionsValueMetadata IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ParameterDefinitionsValueMetadata)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeParameterDefinitionsValueMetadata(document.RootElement, options); - } - - internal static ParameterDefinitionsValueMetadata DeserializeParameterDefinitionsValueMetadata(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string displayName = default; - string description = default; - string strongType = default; - bool? assignPermissions = default; - IDictionary additionalProperties = default; - Dictionary additionalPropertiesDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (property.NameEquals("description"u8)) - { - description = property.Value.GetString(); - continue; - } - if (property.NameEquals("strongType"u8)) - { - strongType = property.Value.GetString(); - continue; - } - if (property.NameEquals("assignPermissions"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - assignPermissions = property.Value.GetBoolean(); - continue; - } - additionalPropertiesDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - additionalProperties = additionalPropertiesDictionary; - return new ParameterDefinitionsValueMetadata(displayName, description, strongType, assignPermissions, additionalProperties); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Description), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" description: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Description)) - { - builder.Append(" description: "); - if (Description.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Description}'''"); - } - else - { - builder.AppendLine($"'{Description}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(StrongType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" strongType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(StrongType)) - { - builder.Append(" strongType: "); - if (StrongType.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{StrongType}'''"); - } - else - { - builder.AppendLine($"'{StrongType}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(AssignPermissions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" assignPermissions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(AssignPermissions)) - { - builder.Append(" assignPermissions: "); - var boolValue = AssignPermissions.Value == true ? "true" : "false"; - builder.AppendLine($"{boolValue}"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ParameterDefinitionsValueMetadata)} does not support writing '{options.Format}' format."); - } - } - - ParameterDefinitionsValueMetadata IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeParameterDefinitionsValueMetadata(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ParameterDefinitionsValueMetadata)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ParameterDefinitionsValueMetadata.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ParameterDefinitionsValueMetadata.cs deleted file mode 100644 index 96ed7496b1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ParameterDefinitionsValueMetadata.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// General metadata for the parameter. - public partial class ParameterDefinitionsValueMetadata - { - /// Initializes a new instance of . - public ParameterDefinitionsValueMetadata() - { - AdditionalProperties = new ChangeTrackingDictionary(); - } - - /// Initializes a new instance of . - /// The display name for the parameter. - /// The description of the parameter. - /// Used when assigning the policy definition through the portal. Provides a context aware list of values for the user to choose from. - /// Set to true to have Azure portal create role assignments on the resource ID or resource scope value of this parameter during policy assignment. This property is useful in case you wish to assign permissions outside the assignment scope. - /// Additional Properties. - internal ParameterDefinitionsValueMetadata(string displayName, string description, string strongType, bool? assignPermissions, IDictionary additionalProperties) - { - DisplayName = displayName; - Description = description; - StrongType = strongType; - AssignPermissions = assignPermissions; - AdditionalProperties = additionalProperties; - } - - /// The display name for the parameter. - [WirePath("displayName")] - public string DisplayName { get; set; } - /// The description of the parameter. - [WirePath("description")] - public string Description { get; set; } - /// Used when assigning the policy definition through the portal. Provides a context aware list of values for the user to choose from. - [WirePath("strongType")] - public string StrongType { get; set; } - /// Set to true to have Azure portal create role assignments on the resource ID or resource scope value of this parameter during policy assignment. This property is useful in case you wish to assign permissions outside the assignment scope. - [WirePath("assignPermissions")] - public bool? AssignPermissions { get; set; } - /// - /// Additional Properties - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("AdditionalProperties")] - public IDictionary AdditionalProperties { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/Permission.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/Permission.Serialization.cs deleted file mode 100644 index fe7d724800..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/Permission.Serialization.cs +++ /dev/null @@ -1,381 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class Permission : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(Permission)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(AllowedActions)) - { - writer.WritePropertyName("actions"u8); - writer.WriteStartArray(); - foreach (var item in AllowedActions) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(DeniedActions)) - { - writer.WritePropertyName("notActions"u8); - writer.WriteStartArray(); - foreach (var item in DeniedActions) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(AllowedDataActions)) - { - writer.WritePropertyName("dataActions"u8); - writer.WriteStartArray(); - foreach (var item in AllowedDataActions) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(DeniedDataActions)) - { - writer.WritePropertyName("notDataActions"u8); - writer.WriteStartArray(); - foreach (var item in DeniedDataActions) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - Permission IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(Permission)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePermission(document.RootElement, options); - } - - internal static Permission DeserializePermission(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList actions = default; - IReadOnlyList notActions = default; - IReadOnlyList dataActions = default; - IReadOnlyList notDataActions = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("actions"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - actions = array; - continue; - } - if (property.NameEquals("notActions"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - notActions = array; - continue; - } - if (property.NameEquals("dataActions"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - dataActions = array; - continue; - } - if (property.NameEquals("notDataActions"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - notDataActions = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new Permission(actions ?? new ChangeTrackingList(), notActions ?? new ChangeTrackingList(), dataActions ?? new ChangeTrackingList(), notDataActions ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(AllowedActions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" actions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(AllowedActions)) - { - if (AllowedActions.Any()) - { - builder.Append(" actions: "); - builder.AppendLine("["); - foreach (var item in AllowedActions) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DeniedActions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" notActions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(DeniedActions)) - { - if (DeniedActions.Any()) - { - builder.Append(" notActions: "); - builder.AppendLine("["); - foreach (var item in DeniedActions) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(AllowedDataActions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" dataActions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(AllowedDataActions)) - { - if (AllowedDataActions.Any()) - { - builder.Append(" dataActions: "); - builder.AppendLine("["); - foreach (var item in AllowedDataActions) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DeniedDataActions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" notDataActions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(DeniedDataActions)) - { - if (DeniedDataActions.Any()) - { - builder.Append(" notDataActions: "); - builder.AppendLine("["); - foreach (var item in DeniedDataActions) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(Permission)} does not support writing '{options.Format}' format."); - } - } - - Permission IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePermission(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(Permission)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/Permission.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/Permission.cs deleted file mode 100644 index 0b614bc2dd..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/Permission.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Role definition permissions. - public partial class Permission - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal Permission() - { - AllowedActions = new ChangeTrackingList(); - DeniedActions = new ChangeTrackingList(); - AllowedDataActions = new ChangeTrackingList(); - DeniedDataActions = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// Allowed actions. - /// Denied actions. - /// Allowed Data actions. - /// Denied Data actions. - /// Keeps track of any properties unknown to the library. - internal Permission(IReadOnlyList allowedActions, IReadOnlyList deniedActions, IReadOnlyList allowedDataActions, IReadOnlyList deniedDataActions, IDictionary serializedAdditionalRawData) - { - AllowedActions = allowedActions; - DeniedActions = deniedActions; - AllowedDataActions = allowedDataActions; - DeniedDataActions = deniedDataActions; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Allowed actions. - [WirePath("actions")] - public IReadOnlyList AllowedActions { get; } - /// Denied actions. - [WirePath("notActions")] - public IReadOnlyList DeniedActions { get; } - /// Allowed Data actions. - [WirePath("dataActions")] - public IReadOnlyList AllowedDataActions { get; } - /// Denied Data actions. - [WirePath("notDataActions")] - public IReadOnlyList DeniedDataActions { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentListResult.Serialization.cs deleted file mode 100644 index 6e769e9894..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class PolicyAssignmentListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyAssignmentListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - PolicyAssignmentListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyAssignmentListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicyAssignmentListResult(document.RootElement, options); - } - - internal static PolicyAssignmentListResult DeserializePolicyAssignmentListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(PolicyAssignmentData.DeserializePolicyAssignmentData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicyAssignmentListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PolicyAssignmentListResult)} does not support writing '{options.Format}' format."); - } - } - - PolicyAssignmentListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicyAssignmentListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicyAssignmentListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentListResult.cs deleted file mode 100644 index 2c650f257a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of policy assignments. - internal partial class PolicyAssignmentListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal PolicyAssignmentListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of policy assignments. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal PolicyAssignmentListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of policy assignments. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentPatch.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentPatch.Serialization.cs deleted file mode 100644 index 098c4203f5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentPatch.Serialization.cs +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class PolicyAssignmentPatch : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyAssignmentPatch)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Location)) - { - writer.WritePropertyName("location"u8); - writer.WriteStringValue(Location.Value); - } - if (Optional.IsDefined(Identity)) - { - writer.WritePropertyName("identity"u8); - JsonSerializer.Serialize(writer, Identity, ResourceManagerJsonContext.Default.ManagedServiceIdentity); - } - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (Optional.IsCollectionDefined(ResourceSelectors)) - { - writer.WritePropertyName("resourceSelectors"u8); - writer.WriteStartArray(); - foreach (var item in ResourceSelectors) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(Overrides)) - { - writer.WritePropertyName("overrides"u8); - writer.WriteStartArray(); - foreach (var item in Overrides) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - writer.WriteEndObject(); - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - PolicyAssignmentPatch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyAssignmentPatch)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicyAssignmentPatch(document.RootElement, options); - } - - internal static PolicyAssignmentPatch DeserializePolicyAssignmentPatch(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - AzureLocation? location = default; - ManagedServiceIdentity identity = default; - IList resourceSelectors = default; - IList overrides = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("location"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - location = new AzureLocation(property.Value.GetString()); - continue; - } - if (property.NameEquals("identity"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - identity = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.ManagedServiceIdentity); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("resourceSelectors"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(ResourceSelector.DeserializeResourceSelector(item, options)); - } - resourceSelectors = array; - continue; - } - if (property0.NameEquals("overrides"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(PolicyOverride.DeserializePolicyOverride(item, options)); - } - overrides = array; - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicyAssignmentPatch(location, identity, resourceSelectors ?? new ChangeTrackingList(), overrides ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(PolicyAssignmentPatch)} does not support writing '{options.Format}' format."); - } - } - - PolicyAssignmentPatch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicyAssignmentPatch(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicyAssignmentPatch)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentPatch.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentPatch.cs deleted file mode 100644 index d85c3fcbad..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentPatch.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The policy assignment for Patch request. - public partial class PolicyAssignmentPatch - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public PolicyAssignmentPatch() - { - ResourceSelectors = new ChangeTrackingList(); - Overrides = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The location of the policy assignment. Only required when utilizing managed identity. - /// The managed identity associated with the policy assignment. Current supported identity types: None, SystemAssigned, UserAssigned. - /// The resource selector list to filter policies by resource properties. - /// The policy property value override. - /// Keeps track of any properties unknown to the library. - internal PolicyAssignmentPatch(AzureLocation? location, ManagedServiceIdentity identity, IList resourceSelectors, IList overrides, IDictionary serializedAdditionalRawData) - { - Location = location; - Identity = identity; - ResourceSelectors = resourceSelectors; - Overrides = overrides; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The location of the policy assignment. Only required when utilizing managed identity. - [WirePath("location")] - public AzureLocation? Location { get; set; } - /// The managed identity associated with the policy assignment. Current supported identity types: None, SystemAssigned, UserAssigned. - [WirePath("identity")] - public ManagedServiceIdentity Identity { get; set; } - /// The resource selector list to filter policies by resource properties. - [WirePath("properties.resourceSelectors")] - public IList ResourceSelectors { get; } - /// The policy property value override. - [WirePath("properties.overrides")] - public IList Overrides { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionGroup.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionGroup.Serialization.cs deleted file mode 100644 index dfd1925207..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionGroup.Serialization.cs +++ /dev/null @@ -1,309 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class PolicyDefinitionGroup : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyDefinitionGroup)} does not support writing '{format}' format."); - } - - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (Optional.IsDefined(Category)) - { - writer.WritePropertyName("category"u8); - writer.WriteStringValue(Category); - } - if (Optional.IsDefined(Description)) - { - writer.WritePropertyName("description"u8); - writer.WriteStringValue(Description); - } - if (Optional.IsDefined(AdditionalMetadataId)) - { - writer.WritePropertyName("additionalMetadataId"u8); - writer.WriteStringValue(AdditionalMetadataId); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - PolicyDefinitionGroup IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyDefinitionGroup)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicyDefinitionGroup(document.RootElement, options); - } - - internal static PolicyDefinitionGroup DeserializePolicyDefinitionGroup(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - string displayName = default; - string category = default; - string description = default; - string additionalMetadataId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (property.NameEquals("category"u8)) - { - category = property.Value.GetString(); - continue; - } - if (property.NameEquals("description"u8)) - { - description = property.Value.GetString(); - continue; - } - if (property.NameEquals("additionalMetadataId"u8)) - { - additionalMetadataId = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicyDefinitionGroup( - name, - displayName, - category, - description, - additionalMetadataId, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Category), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" category: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Category)) - { - builder.Append(" category: "); - if (Category.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Category}'''"); - } - else - { - builder.AppendLine($"'{Category}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Description), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" description: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Description)) - { - builder.Append(" description: "); - if (Description.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Description}'''"); - } - else - { - builder.AppendLine($"'{Description}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(AdditionalMetadataId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" additionalMetadataId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(AdditionalMetadataId)) - { - builder.Append(" additionalMetadataId: "); - if (AdditionalMetadataId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{AdditionalMetadataId}'''"); - } - else - { - builder.AppendLine($"'{AdditionalMetadataId}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PolicyDefinitionGroup)} does not support writing '{options.Format}' format."); - } - } - - PolicyDefinitionGroup IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicyDefinitionGroup(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicyDefinitionGroup)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionGroup.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionGroup.cs deleted file mode 100644 index 9f18d09866..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionGroup.cs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The policy definition group. - public partial class PolicyDefinitionGroup - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The name of the group. - /// is null. - public PolicyDefinitionGroup(string name) - { - Argument.AssertNotNull(name, nameof(name)); - - Name = name; - } - - /// Initializes a new instance of . - /// The name of the group. - /// The group's display name. - /// The group's category. - /// The group's description. - /// A resource ID of a resource that contains additional metadata about the group. - /// Keeps track of any properties unknown to the library. - internal PolicyDefinitionGroup(string name, string displayName, string category, string description, string additionalMetadataId, IDictionary serializedAdditionalRawData) - { - Name = name; - DisplayName = displayName; - Category = category; - Description = description; - AdditionalMetadataId = additionalMetadataId; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal PolicyDefinitionGroup() - { - } - - /// The name of the group. - [WirePath("name")] - public string Name { get; set; } - /// The group's display name. - [WirePath("displayName")] - public string DisplayName { get; set; } - /// The group's category. - [WirePath("category")] - public string Category { get; set; } - /// The group's description. - [WirePath("description")] - public string Description { get; set; } - /// A resource ID of a resource that contains additional metadata about the group. - [WirePath("additionalMetadataId")] - public string AdditionalMetadataId { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionListResult.Serialization.cs deleted file mode 100644 index 34758a66f0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class PolicyDefinitionListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyDefinitionListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - PolicyDefinitionListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyDefinitionListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicyDefinitionListResult(document.RootElement, options); - } - - internal static PolicyDefinitionListResult DeserializePolicyDefinitionListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(PolicyDefinitionData.DeserializePolicyDefinitionData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicyDefinitionListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PolicyDefinitionListResult)} does not support writing '{options.Format}' format."); - } - } - - PolicyDefinitionListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicyDefinitionListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicyDefinitionListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionListResult.cs deleted file mode 100644 index c09165e0d9..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of policy definitions. - internal partial class PolicyDefinitionListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal PolicyDefinitionListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of policy definitions. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal PolicyDefinitionListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of policy definitions. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionReference.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionReference.Serialization.cs deleted file mode 100644 index dbbf48365e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionReference.Serialization.cs +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class PolicyDefinitionReference : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyDefinitionReference)} does not support writing '{format}' format."); - } - - writer.WritePropertyName("policyDefinitionId"u8); - writer.WriteStringValue(PolicyDefinitionId); - if (Optional.IsCollectionDefined(Parameters)) - { - writer.WritePropertyName("parameters"u8); - writer.WriteStartObject(); - foreach (var item in Parameters) - { - writer.WritePropertyName(item.Key); - writer.WriteObjectValue(item.Value, options); - } - writer.WriteEndObject(); - } - if (Optional.IsDefined(PolicyDefinitionReferenceId)) - { - writer.WritePropertyName("policyDefinitionReferenceId"u8); - writer.WriteStringValue(PolicyDefinitionReferenceId); - } - if (Optional.IsCollectionDefined(GroupNames)) - { - writer.WritePropertyName("groupNames"u8); - writer.WriteStartArray(); - foreach (var item in GroupNames) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - PolicyDefinitionReference IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyDefinitionReference)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicyDefinitionReference(document.RootElement, options); - } - - internal static PolicyDefinitionReference DeserializePolicyDefinitionReference(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string policyDefinitionId = default; - IDictionary parameters = default; - string policyDefinitionReferenceId = default; - IList groupNames = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("policyDefinitionId"u8)) - { - policyDefinitionId = property.Value.GetString(); - continue; - } - if (property.NameEquals("parameters"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, ArmPolicyParameterValue.DeserializeArmPolicyParameterValue(property0.Value, options)); - } - parameters = dictionary; - continue; - } - if (property.NameEquals("policyDefinitionReferenceId"u8)) - { - policyDefinitionReferenceId = property.Value.GetString(); - continue; - } - if (property.NameEquals("groupNames"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - groupNames = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicyDefinitionReference(policyDefinitionId, parameters ?? new ChangeTrackingDictionary(), policyDefinitionReferenceId, groupNames ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyDefinitionId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyDefinitionId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PolicyDefinitionId)) - { - builder.Append(" policyDefinitionId: "); - if (PolicyDefinitionId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{PolicyDefinitionId}'''"); - } - else - { - builder.AppendLine($"'{PolicyDefinitionId}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Parameters), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parameters: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Parameters)) - { - if (Parameters.Any()) - { - builder.Append(" parameters: "); - builder.AppendLine("{"); - foreach (var item in Parameters) - { - builder.Append($" '{item.Key}': "); - BicepSerializationHelpers.AppendChildObject(builder, item.Value, options, 4, false, " parameters: "); - } - builder.AppendLine(" }"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyDefinitionReferenceId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyDefinitionReferenceId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PolicyDefinitionReferenceId)) - { - builder.Append(" policyDefinitionReferenceId: "); - if (PolicyDefinitionReferenceId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{PolicyDefinitionReferenceId}'''"); - } - else - { - builder.AppendLine($"'{PolicyDefinitionReferenceId}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(GroupNames), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" groupNames: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(GroupNames)) - { - if (GroupNames.Any()) - { - builder.Append(" groupNames: "); - builder.AppendLine("["); - foreach (var item in GroupNames) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PolicyDefinitionReference)} does not support writing '{options.Format}' format."); - } - } - - PolicyDefinitionReference IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicyDefinitionReference(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicyDefinitionReference)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionReference.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionReference.cs deleted file mode 100644 index da023f91ac..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionReference.cs +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The policy definition reference. - public partial class PolicyDefinitionReference - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The ID of the policy definition or policy set definition. - /// is null. - public PolicyDefinitionReference(string policyDefinitionId) - { - Argument.AssertNotNull(policyDefinitionId, nameof(policyDefinitionId)); - - PolicyDefinitionId = policyDefinitionId; - Parameters = new ChangeTrackingDictionary(); - GroupNames = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The ID of the policy definition or policy set definition. - /// The parameter values for the referenced policy rule. The keys are the parameter names. - /// A unique id (within the policy set definition) for this policy definition reference. - /// The name of the groups that this policy definition reference belongs to. - /// Keeps track of any properties unknown to the library. - internal PolicyDefinitionReference(string policyDefinitionId, IDictionary parameters, string policyDefinitionReferenceId, IList groupNames, IDictionary serializedAdditionalRawData) - { - PolicyDefinitionId = policyDefinitionId; - Parameters = parameters; - PolicyDefinitionReferenceId = policyDefinitionReferenceId; - GroupNames = groupNames; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal PolicyDefinitionReference() - { - } - - /// The ID of the policy definition or policy set definition. - [WirePath("policyDefinitionId")] - public string PolicyDefinitionId { get; set; } - /// The parameter values for the referenced policy rule. The keys are the parameter names. - [WirePath("parameters")] - public IDictionary Parameters { get; } - /// A unique id (within the policy set definition) for this policy definition reference. - [WirePath("policyDefinitionReferenceId")] - public string PolicyDefinitionReferenceId { get; set; } - /// The name of the groups that this policy definition reference belongs to. - [WirePath("groupNames")] - public IList GroupNames { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverride.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverride.Serialization.cs deleted file mode 100644 index 71ce671e03..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverride.Serialization.cs +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class PolicyOverride : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyOverride)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Kind)) - { - writer.WritePropertyName("kind"u8); - writer.WriteStringValue(Kind.Value.ToString()); - } - if (Optional.IsDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStringValue(Value); - } - if (Optional.IsCollectionDefined(Selectors)) - { - writer.WritePropertyName("selectors"u8); - writer.WriteStartArray(); - foreach (var item in Selectors) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - PolicyOverride IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyOverride)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicyOverride(document.RootElement, options); - } - - internal static PolicyOverride DeserializePolicyOverride(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - PolicyOverrideKind? kind = default; - string value = default; - IList selectors = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("kind"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - kind = new PolicyOverrideKind(property.Value.GetString()); - continue; - } - if (property.NameEquals("value"u8)) - { - value = property.Value.GetString(); - continue; - } - if (property.NameEquals("selectors"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ResourceSelectorExpression.DeserializeResourceSelectorExpression(item, options)); - } - selectors = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicyOverride(kind, value, selectors ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Kind), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" kind: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Kind)) - { - builder.Append(" kind: "); - builder.AppendLine($"'{Kind.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Value)) - { - builder.Append(" value: "); - if (Value.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Value}'''"); - } - else - { - builder.AppendLine($"'{Value}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Selectors), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" selectors: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Selectors)) - { - if (Selectors.Any()) - { - builder.Append(" selectors: "); - builder.AppendLine("["); - foreach (var item in Selectors) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " selectors: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PolicyOverride)} does not support writing '{options.Format}' format."); - } - } - - PolicyOverride IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicyOverride(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicyOverride)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverride.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverride.cs deleted file mode 100644 index d546bbcfa3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverride.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The policy property value override. - public partial class PolicyOverride - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public PolicyOverride() - { - Selectors = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The override kind. - /// The value to override the policy property. - /// The list of the selector expressions. - /// Keeps track of any properties unknown to the library. - internal PolicyOverride(PolicyOverrideKind? kind, string value, IList selectors, IDictionary serializedAdditionalRawData) - { - Kind = kind; - Value = value; - Selectors = selectors; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The override kind. - [WirePath("kind")] - public PolicyOverrideKind? Kind { get; set; } - /// The value to override the policy property. - [WirePath("value")] - public string Value { get; set; } - /// The list of the selector expressions. - [WirePath("selectors")] - public IList Selectors { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverrideKind.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverrideKind.cs deleted file mode 100644 index 1529755b23..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverrideKind.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The override kind. - public readonly partial struct PolicyOverrideKind : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public PolicyOverrideKind(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string PolicyEffectValue = "policyEffect"; - - /// It will override the policy effect type. - public static PolicyOverrideKind PolicyEffect { get; } = new PolicyOverrideKind(PolicyEffectValue); - /// Determines if two values are the same. - public static bool operator ==(PolicyOverrideKind left, PolicyOverrideKind right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(PolicyOverrideKind left, PolicyOverrideKind right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator PolicyOverrideKind(string value) => new PolicyOverrideKind(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is PolicyOverrideKind other && Equals(other); - /// - public bool Equals(PolicyOverrideKind other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicySetDefinitionListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicySetDefinitionListResult.Serialization.cs deleted file mode 100644 index 87f0ac4fc5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicySetDefinitionListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class PolicySetDefinitionListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicySetDefinitionListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - PolicySetDefinitionListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicySetDefinitionListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicySetDefinitionListResult(document.RootElement, options); - } - - internal static PolicySetDefinitionListResult DeserializePolicySetDefinitionListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(PolicySetDefinitionData.DeserializePolicySetDefinitionData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicySetDefinitionListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PolicySetDefinitionListResult)} does not support writing '{options.Format}' format."); - } - } - - PolicySetDefinitionListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicySetDefinitionListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicySetDefinitionListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicySetDefinitionListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicySetDefinitionListResult.cs deleted file mode 100644 index 7077003141..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicySetDefinitionListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of policy set definitions. - internal partial class PolicySetDefinitionListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal PolicySetDefinitionListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of policy set definitions. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal PolicySetDefinitionListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of policy set definitions. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyType.cs deleted file mode 100644 index 9f88c1c72e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PolicyType.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static. - public readonly partial struct PolicyType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public PolicyType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string NotSpecifiedValue = "NotSpecified"; - private const string BuiltInValue = "BuiltIn"; - private const string CustomValue = "Custom"; - private const string StaticValue = "Static"; - - /// NotSpecified. - public static PolicyType NotSpecified { get; } = new PolicyType(NotSpecifiedValue); - /// BuiltIn. - public static PolicyType BuiltIn { get; } = new PolicyType(BuiltInValue); - /// Custom. - public static PolicyType Custom { get; } = new PolicyType(CustomValue); - /// Static. - public static PolicyType Static { get; } = new PolicyType(StaticValue); - /// Determines if two values are the same. - public static bool operator ==(PolicyType left, PolicyType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(PolicyType left, PolicyType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator PolicyType(string value) => new PolicyType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is PolicyType other && Equals(other); - /// - public bool Equals(PolicyType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTag.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTag.Serialization.cs deleted file mode 100644 index 07840949b9..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTag.Serialization.cs +++ /dev/null @@ -1,283 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class PredefinedTag : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PredefinedTag)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (Optional.IsDefined(TagName)) - { - writer.WritePropertyName("tagName"u8); - writer.WriteStringValue(TagName); - } - if (Optional.IsDefined(Count)) - { - writer.WritePropertyName("count"u8); - writer.WriteObjectValue(Count, options); - } - if (Optional.IsCollectionDefined(Values)) - { - writer.WritePropertyName("values"u8); - writer.WriteStartArray(); - foreach (var item in Values) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - PredefinedTag IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PredefinedTag)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePredefinedTag(document.RootElement, options); - } - - internal static PredefinedTag DeserializePredefinedTag(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string id = default; - string tagName = default; - PredefinedTagCount count = default; - IReadOnlyList values = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("tagName"u8)) - { - tagName = property.Value.GetString(); - continue; - } - if (property.NameEquals("count"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - count = PredefinedTagCount.DeserializePredefinedTagCount(property.Value, options); - continue; - } - if (property.NameEquals("values"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(PredefinedTagValue.DeserializePredefinedTagValue(item, options)); - } - values = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PredefinedTag(id, tagName, count, values ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - if (Id.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Id}'''"); - } - else - { - builder.AppendLine($"'{Id}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TagName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tagName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TagName)) - { - builder.Append(" tagName: "); - if (TagName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{TagName}'''"); - } - else - { - builder.AppendLine($"'{TagName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Count), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" count: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Count)) - { - builder.Append(" count: "); - BicepSerializationHelpers.AppendChildObject(builder, Count, options, 2, false, " count: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Values), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" values: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Values)) - { - if (Values.Any()) - { - builder.Append(" values: "); - builder.AppendLine("["); - foreach (var item in Values) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " values: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PredefinedTag)} does not support writing '{options.Format}' format."); - } - } - - PredefinedTag IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePredefinedTag(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PredefinedTag)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTag.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTag.cs deleted file mode 100644 index a929577cd8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTag.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Tag details. - public partial class PredefinedTag - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal PredefinedTag() - { - Values = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The tag name ID. - /// The tag name. - /// The total number of resources that use the resource tag. When a tag is initially created and has no associated resources, the value is 0. - /// The list of tag values. - /// Keeps track of any properties unknown to the library. - internal PredefinedTag(string id, string tagName, PredefinedTagCount count, IReadOnlyList values, IDictionary serializedAdditionalRawData) - { - Id = id; - TagName = tagName; - Count = count; - Values = values; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The tag name ID. - [WirePath("id")] - public string Id { get; } - /// The tag name. - [WirePath("tagName")] - public string TagName { get; } - /// The total number of resources that use the resource tag. When a tag is initially created and has no associated resources, the value is 0. - [WirePath("count")] - public PredefinedTagCount Count { get; } - /// The list of tag values. - [WirePath("values")] - public IReadOnlyList Values { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagCount.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagCount.Serialization.cs deleted file mode 100644 index 2cd1a8683b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagCount.Serialization.cs +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class PredefinedTagCount : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PredefinedTagCount)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(PredefinedTagCountType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(PredefinedTagCountType); - } - if (Optional.IsDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteNumberValue(Value.Value); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - PredefinedTagCount IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PredefinedTagCount)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePredefinedTagCount(document.RootElement, options); - } - - internal static PredefinedTagCount DeserializePredefinedTagCount(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string type = default; - int? value = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - value = property.Value.GetInt32(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PredefinedTagCount(type, value, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PredefinedTagCountType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" type: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PredefinedTagCountType)) - { - builder.Append(" type: "); - if (PredefinedTagCountType.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{PredefinedTagCountType}'''"); - } - else - { - builder.AppendLine($"'{PredefinedTagCountType}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Value)) - { - builder.Append(" value: "); - builder.AppendLine($"{Value.Value}"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PredefinedTagCount)} does not support writing '{options.Format}' format."); - } - } - - PredefinedTagCount IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePredefinedTagCount(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PredefinedTagCount)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagCount.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagCount.cs deleted file mode 100644 index b7d6360ac8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagCount.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Tag count. - public partial class PredefinedTagCount - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal PredefinedTagCount() - { - } - - /// Initializes a new instance of . - /// Type of count. - /// Value of count. - /// Keeps track of any properties unknown to the library. - internal PredefinedTagCount(string predefinedTagCountType, int? value, IDictionary serializedAdditionalRawData) - { - PredefinedTagCountType = predefinedTagCountType; - Value = value; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Type of count. - [WirePath("type")] - public string PredefinedTagCountType { get; } - /// Value of count. - [WirePath("value")] - public int? Value { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagValue.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagValue.Serialization.cs deleted file mode 100644 index 9c1f4d002c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagValue.Serialization.cs +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class PredefinedTagValue : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PredefinedTagValue)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (Optional.IsDefined(TagValue)) - { - writer.WritePropertyName("tagValue"u8); - writer.WriteStringValue(TagValue); - } - if (Optional.IsDefined(Count)) - { - writer.WritePropertyName("count"u8); - writer.WriteObjectValue(Count, options); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - PredefinedTagValue IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PredefinedTagValue)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePredefinedTagValue(document.RootElement, options); - } - - internal static PredefinedTagValue DeserializePredefinedTagValue(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string id = default; - string tagValue = default; - PredefinedTagCount count = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("tagValue"u8)) - { - tagValue = property.Value.GetString(); - continue; - } - if (property.NameEquals("count"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - count = PredefinedTagCount.DeserializePredefinedTagCount(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PredefinedTagValue(id, tagValue, count, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - if (Id.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Id}'''"); - } - else - { - builder.AppendLine($"'{Id}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TagValue), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tagValue: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TagValue)) - { - builder.Append(" tagValue: "); - if (TagValue.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{TagValue}'''"); - } - else - { - builder.AppendLine($"'{TagValue}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Count), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" count: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Count)) - { - builder.Append(" count: "); - BicepSerializationHelpers.AppendChildObject(builder, Count, options, 2, false, " count: "); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PredefinedTagValue)} does not support writing '{options.Format}' format."); - } - } - - PredefinedTagValue IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePredefinedTagValue(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PredefinedTagValue)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagValue.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagValue.cs deleted file mode 100644 index 7c91e6cc59..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagValue.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Tag information. - public partial class PredefinedTagValue - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal PredefinedTagValue() - { - } - - /// Initializes a new instance of . - /// The tag value ID. - /// The tag value. - /// The tag value count. - /// Keeps track of any properties unknown to the library. - internal PredefinedTagValue(string id, string tagValue, PredefinedTagCount count, IDictionary serializedAdditionalRawData) - { - Id = id; - TagValue = tagValue; - Count = count; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The tag value ID. - [WirePath("id")] - public string Id { get; } - /// The tag value. - [WirePath("tagValue")] - public string TagValue { get; } - /// The tag value count. - [WirePath("count")] - public PredefinedTagCount Count { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagsListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagsListResult.Serialization.cs deleted file mode 100644 index bea1bd024f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagsListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class PredefinedTagsListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PredefinedTagsListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - PredefinedTagsListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PredefinedTagsListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePredefinedTagsListResult(document.RootElement, options); - } - - internal static PredefinedTagsListResult DeserializePredefinedTagsListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(PredefinedTag.DeserializePredefinedTag(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PredefinedTagsListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PredefinedTagsListResult)} does not support writing '{options.Format}' format."); - } - } - - PredefinedTagsListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePredefinedTagsListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PredefinedTagsListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagsListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagsListResult.cs deleted file mode 100644 index dc4cc163ff..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagsListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of subscription tags. - internal partial class PredefinedTagsListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal PredefinedTagsListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of tags. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal PredefinedTagsListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of tags. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderAuthorizationConsentState.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderAuthorizationConsentState.cs deleted file mode 100644 index 70a7ad1aa3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderAuthorizationConsentState.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The provider authorization consent state. - public readonly partial struct ProviderAuthorizationConsentState : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ProviderAuthorizationConsentState(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string NotSpecifiedValue = "NotSpecified"; - private const string RequiredValue = "Required"; - private const string NotRequiredValue = "NotRequired"; - private const string ConsentedValue = "Consented"; - - /// NotSpecified. - public static ProviderAuthorizationConsentState NotSpecified { get; } = new ProviderAuthorizationConsentState(NotSpecifiedValue); - /// Required. - public static ProviderAuthorizationConsentState Required { get; } = new ProviderAuthorizationConsentState(RequiredValue); - /// NotRequired. - public static ProviderAuthorizationConsentState NotRequired { get; } = new ProviderAuthorizationConsentState(NotRequiredValue); - /// Consented. - public static ProviderAuthorizationConsentState Consented { get; } = new ProviderAuthorizationConsentState(ConsentedValue); - /// Determines if two values are the same. - public static bool operator ==(ProviderAuthorizationConsentState left, ProviderAuthorizationConsentState right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ProviderAuthorizationConsentState left, ProviderAuthorizationConsentState right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ProviderAuthorizationConsentState(string value) => new ProviderAuthorizationConsentState(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ProviderAuthorizationConsentState other && Equals(other); - /// - public bool Equals(ProviderAuthorizationConsentState other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderConsentDefinition.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderConsentDefinition.Serialization.cs deleted file mode 100644 index 71de2d86a9..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderConsentDefinition.Serialization.cs +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class ProviderConsentDefinition : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderConsentDefinition)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(ConsentToAuthorization)) - { - writer.WritePropertyName("consentToAuthorization"u8); - writer.WriteBooleanValue(ConsentToAuthorization.Value); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ProviderConsentDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderConsentDefinition)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeProviderConsentDefinition(document.RootElement, options); - } - - internal static ProviderConsentDefinition DeserializeProviderConsentDefinition(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - bool? consentToAuthorization = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("consentToAuthorization"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - consentToAuthorization = property.Value.GetBoolean(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ProviderConsentDefinition(consentToAuthorization, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ProviderConsentDefinition)} does not support writing '{options.Format}' format."); - } - } - - ProviderConsentDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeProviderConsentDefinition(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ProviderConsentDefinition)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderConsentDefinition.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderConsentDefinition.cs deleted file mode 100644 index 92b4c29858..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderConsentDefinition.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The provider consent. - internal partial class ProviderConsentDefinition - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ProviderConsentDefinition() - { - } - - /// Initializes a new instance of . - /// A value indicating whether authorization is consented or not. - /// Keeps track of any properties unknown to the library. - internal ProviderConsentDefinition(bool? consentToAuthorization, IDictionary serializedAdditionalRawData) - { - ConsentToAuthorization = consentToAuthorization; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// A value indicating whether authorization is consented or not. - [WirePath("consentToAuthorization")] - public bool? ConsentToAuthorization { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderExtendedLocation.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderExtendedLocation.Serialization.cs deleted file mode 100644 index d1b0f54781..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderExtendedLocation.Serialization.cs +++ /dev/null @@ -1,262 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ProviderExtendedLocation : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderExtendedLocation)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Location)) - { - writer.WritePropertyName("location"u8); - writer.WriteStringValue(Location.Value); - } - if (Optional.IsDefined(ProviderExtendedLocationType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ProviderExtendedLocationType); - } - if (Optional.IsCollectionDefined(ExtendedLocations)) - { - writer.WritePropertyName("extendedLocations"u8); - writer.WriteStartArray(); - foreach (var item in ExtendedLocations) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ProviderExtendedLocation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderExtendedLocation)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeProviderExtendedLocation(document.RootElement, options); - } - - internal static ProviderExtendedLocation DeserializeProviderExtendedLocation(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - AzureLocation? location = default; - string type = default; - IReadOnlyList extendedLocations = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("location"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - location = new AzureLocation(property.Value.GetString()); - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (property.NameEquals("extendedLocations"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - extendedLocations = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ProviderExtendedLocation(location, type, extendedLocations ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Location), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" location: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Location)) - { - builder.Append(" location: "); - builder.AppendLine($"'{Location.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ProviderExtendedLocationType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" type: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ProviderExtendedLocationType)) - { - builder.Append(" type: "); - if (ProviderExtendedLocationType.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ProviderExtendedLocationType}'''"); - } - else - { - builder.AppendLine($"'{ProviderExtendedLocationType}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ExtendedLocations), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" extendedLocations: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ExtendedLocations)) - { - if (ExtendedLocations.Any()) - { - builder.Append(" extendedLocations: "); - builder.AppendLine("["); - foreach (var item in ExtendedLocations) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ProviderExtendedLocation)} does not support writing '{options.Format}' format."); - } - } - - ProviderExtendedLocation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeProviderExtendedLocation(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ProviderExtendedLocation)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderExtendedLocation.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderExtendedLocation.cs deleted file mode 100644 index 3b129aeeb0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderExtendedLocation.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The provider extended location. - public partial class ProviderExtendedLocation - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ProviderExtendedLocation() - { - ExtendedLocations = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The azure location. - /// The extended location type. - /// The extended locations for the azure location. - /// Keeps track of any properties unknown to the library. - internal ProviderExtendedLocation(AzureLocation? location, string providerExtendedLocationType, IReadOnlyList extendedLocations, IDictionary serializedAdditionalRawData) - { - Location = location; - ProviderExtendedLocationType = providerExtendedLocationType; - ExtendedLocations = extendedLocations; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The azure location. - [WirePath("location")] - public AzureLocation? Location { get; } - /// The extended location type. - [WirePath("type")] - public string ProviderExtendedLocationType { get; } - /// The extended locations for the azure location. - [WirePath("extendedLocations")] - public IReadOnlyList ExtendedLocations { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermission.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermission.Serialization.cs deleted file mode 100644 index ce8f48ce4a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermission.Serialization.cs +++ /dev/null @@ -1,260 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ProviderPermission : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderPermission)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(ApplicationId)) - { - writer.WritePropertyName("applicationId"u8); - writer.WriteStringValue(ApplicationId); - } - if (Optional.IsDefined(RoleDefinition)) - { - writer.WritePropertyName("roleDefinition"u8); - writer.WriteObjectValue(RoleDefinition, options); - } - if (Optional.IsDefined(ManagedByRoleDefinition)) - { - writer.WritePropertyName("managedByRoleDefinition"u8); - writer.WriteObjectValue(ManagedByRoleDefinition, options); - } - if (Optional.IsDefined(ProviderAuthorizationConsentState)) - { - writer.WritePropertyName("providerAuthorizationConsentState"u8); - writer.WriteStringValue(ProviderAuthorizationConsentState.Value.ToString()); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ProviderPermission IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderPermission)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeProviderPermission(document.RootElement, options); - } - - internal static ProviderPermission DeserializeProviderPermission(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string applicationId = default; - AzureRoleDefinition roleDefinition = default; - AzureRoleDefinition managedByRoleDefinition = default; - ProviderAuthorizationConsentState? providerAuthorizationConsentState = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("applicationId"u8)) - { - applicationId = property.Value.GetString(); - continue; - } - if (property.NameEquals("roleDefinition"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - roleDefinition = AzureRoleDefinition.DeserializeAzureRoleDefinition(property.Value, options); - continue; - } - if (property.NameEquals("managedByRoleDefinition"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - managedByRoleDefinition = AzureRoleDefinition.DeserializeAzureRoleDefinition(property.Value, options); - continue; - } - if (property.NameEquals("providerAuthorizationConsentState"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - providerAuthorizationConsentState = new ProviderAuthorizationConsentState(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ProviderPermission(applicationId, roleDefinition, managedByRoleDefinition, providerAuthorizationConsentState, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ApplicationId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" applicationId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ApplicationId)) - { - builder.Append(" applicationId: "); - if (ApplicationId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ApplicationId}'''"); - } - else - { - builder.AppendLine($"'{ApplicationId}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(RoleDefinition), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" roleDefinition: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(RoleDefinition)) - { - builder.Append(" roleDefinition: "); - BicepSerializationHelpers.AppendChildObject(builder, RoleDefinition, options, 2, false, " roleDefinition: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ManagedByRoleDefinition), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" managedByRoleDefinition: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ManagedByRoleDefinition)) - { - builder.Append(" managedByRoleDefinition: "); - BicepSerializationHelpers.AppendChildObject(builder, ManagedByRoleDefinition, options, 2, false, " managedByRoleDefinition: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ProviderAuthorizationConsentState), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" providerAuthorizationConsentState: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ProviderAuthorizationConsentState)) - { - builder.Append(" providerAuthorizationConsentState: "); - builder.AppendLine($"'{ProviderAuthorizationConsentState.Value.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ProviderPermission)} does not support writing '{options.Format}' format."); - } - } - - ProviderPermission IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeProviderPermission(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ProviderPermission)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermission.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermission.cs deleted file mode 100644 index b8dbd24538..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermission.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The provider permission. - public partial class ProviderPermission - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ProviderPermission() - { - } - - /// Initializes a new instance of . - /// The application id. - /// Role definition properties. - /// Role definition properties. - /// The provider authorization consent state. - /// Keeps track of any properties unknown to the library. - internal ProviderPermission(string applicationId, AzureRoleDefinition roleDefinition, AzureRoleDefinition managedByRoleDefinition, ProviderAuthorizationConsentState? providerAuthorizationConsentState, IDictionary serializedAdditionalRawData) - { - ApplicationId = applicationId; - RoleDefinition = roleDefinition; - ManagedByRoleDefinition = managedByRoleDefinition; - ProviderAuthorizationConsentState = providerAuthorizationConsentState; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The application id. - [WirePath("applicationId")] - public string ApplicationId { get; } - /// Role definition properties. - [WirePath("roleDefinition")] - public AzureRoleDefinition RoleDefinition { get; } - /// Role definition properties. - [WirePath("managedByRoleDefinition")] - public AzureRoleDefinition ManagedByRoleDefinition { get; } - /// The provider authorization consent state. - [WirePath("providerAuthorizationConsentState")] - public ProviderAuthorizationConsentState? ProviderAuthorizationConsentState { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermissionListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermissionListResult.Serialization.cs deleted file mode 100644 index b4082c199c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermissionListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class ProviderPermissionListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderPermissionListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ProviderPermissionListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderPermissionListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeProviderPermissionListResult(document.RootElement, options); - } - - internal static ProviderPermissionListResult DeserializeProviderPermissionListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ProviderPermission.DeserializeProviderPermission(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ProviderPermissionListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ProviderPermissionListResult)} does not support writing '{options.Format}' format."); - } - } - - ProviderPermissionListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeProviderPermissionListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ProviderPermissionListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermissionListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermissionListResult.cs deleted file mode 100644 index bfb5b6bbb2..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermissionListResult.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of provider permissions. - internal partial class ProviderPermissionListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ProviderPermissionListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of provider permissions. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal ProviderPermissionListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of provider permissions. - [WirePath("value")] - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - [WirePath("nextLink")] - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderRegistrationContent.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderRegistrationContent.Serialization.cs deleted file mode 100644 index 616d8a93e7..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderRegistrationContent.Serialization.cs +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ProviderRegistrationContent : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderRegistrationContent)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(ThirdPartyProviderConsent)) - { - writer.WritePropertyName("thirdPartyProviderConsent"u8); - writer.WriteObjectValue(ThirdPartyProviderConsent, options); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ProviderRegistrationContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderRegistrationContent)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeProviderRegistrationContent(document.RootElement, options); - } - - internal static ProviderRegistrationContent DeserializeProviderRegistrationContent(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ProviderConsentDefinition thirdPartyProviderConsent = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("thirdPartyProviderConsent"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - thirdPartyProviderConsent = ProviderConsentDefinition.DeserializeProviderConsentDefinition(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ProviderRegistrationContent(thirdPartyProviderConsent, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ProviderRegistrationContent)} does not support writing '{options.Format}' format."); - } - } - - ProviderRegistrationContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeProviderRegistrationContent(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ProviderRegistrationContent)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderRegistrationContent.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderRegistrationContent.cs deleted file mode 100644 index 92eb16dbd6..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderRegistrationContent.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The provider registration definition. - public partial class ProviderRegistrationContent - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ProviderRegistrationContent() - { - } - - /// Initializes a new instance of . - /// The provider consent. - /// Keeps track of any properties unknown to the library. - internal ProviderRegistrationContent(ProviderConsentDefinition thirdPartyProviderConsent, IDictionary serializedAdditionalRawData) - { - ThirdPartyProviderConsent = thirdPartyProviderConsent; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The provider consent. - internal ProviderConsentDefinition ThirdPartyProviderConsent { get; set; } - /// A value indicating whether authorization is consented or not. - [WirePath("thirdPartyProviderConsent.consentToAuthorization")] - public bool? ConsentToAuthorization - { - get => ThirdPartyProviderConsent is null ? default : ThirdPartyProviderConsent.ConsentToAuthorization; - set - { - if (ThirdPartyProviderConsent is null) - ThirdPartyProviderConsent = new ProviderConsentDefinition(); - ThirdPartyProviderConsent.ConsentToAuthorization = value; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceType.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceType.Serialization.cs deleted file mode 100644 index 47c4501434..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceType.Serialization.cs +++ /dev/null @@ -1,627 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ProviderResourceType : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderResourceType)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(ResourceType)) - { - writer.WritePropertyName("resourceType"u8); - writer.WriteStringValue(ResourceType); - } - if (Optional.IsCollectionDefined(Locations)) - { - writer.WritePropertyName("locations"u8); - writer.WriteStartArray(); - foreach (var item in Locations) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(LocationMappings)) - { - writer.WritePropertyName("locationMappings"u8); - writer.WriteStartArray(); - foreach (var item in LocationMappings) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(Aliases)) - { - writer.WritePropertyName("aliases"u8); - writer.WriteStartArray(); - foreach (var item in Aliases) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(ApiVersions)) - { - writer.WritePropertyName("apiVersions"u8); - writer.WriteStartArray(); - foreach (var item in ApiVersions) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(DefaultApiVersion)) - { - writer.WritePropertyName("defaultApiVersion"u8); - writer.WriteStringValue(DefaultApiVersion); - } - if (Optional.IsCollectionDefined(ZoneMappings)) - { - writer.WritePropertyName("zoneMappings"u8); - writer.WriteStartArray(); - foreach (var item in ZoneMappings) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsCollectionDefined(ApiProfiles)) - { - writer.WritePropertyName("apiProfiles"u8); - writer.WriteStartArray(); - foreach (var item in ApiProfiles) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(Capabilities)) - { - writer.WritePropertyName("capabilities"u8); - writer.WriteStringValue(Capabilities); - } - if (Optional.IsCollectionDefined(Properties)) - { - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - foreach (var item in Properties) - { - writer.WritePropertyName(item.Key); - writer.WriteStringValue(item.Value); - } - writer.WriteEndObject(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ProviderResourceType IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderResourceType)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeProviderResourceType(document.RootElement, options); - } - - internal static ProviderResourceType DeserializeProviderResourceType(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string resourceType = default; - IReadOnlyList locations = default; - IReadOnlyList locationMappings = default; - IReadOnlyList aliases = default; - IReadOnlyList apiVersions = default; - string defaultApiVersion = default; - IReadOnlyList zoneMappings = default; - IReadOnlyList apiProfiles = default; - string capabilities = default; - IReadOnlyDictionary properties = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("resourceType"u8)) - { - resourceType = property.Value.GetString(); - continue; - } - if (property.NameEquals("locations"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - locations = array; - continue; - } - if (property.NameEquals("locationMappings"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ProviderExtendedLocation.DeserializeProviderExtendedLocation(item, options)); - } - locationMappings = array; - continue; - } - if (property.NameEquals("aliases"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ResourceTypeAlias.DeserializeResourceTypeAlias(item, options)); - } - aliases = array; - continue; - } - if (property.NameEquals("apiVersions"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - apiVersions = array; - continue; - } - if (property.NameEquals("defaultApiVersion"u8)) - { - defaultApiVersion = property.Value.GetString(); - continue; - } - if (property.NameEquals("zoneMappings"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ZoneMapping.DeserializeZoneMapping(item, options)); - } - zoneMappings = array; - continue; - } - if (property.NameEquals("apiProfiles"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ApiProfile.DeserializeApiProfile(item, options)); - } - apiProfiles = array; - continue; - } - if (property.NameEquals("capabilities"u8)) - { - capabilities = property.Value.GetString(); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - properties = dictionary; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ProviderResourceType( - resourceType, - locations ?? new ChangeTrackingList(), - locationMappings ?? new ChangeTrackingList(), - aliases ?? new ChangeTrackingList(), - apiVersions ?? new ChangeTrackingList(), - defaultApiVersion, - zoneMappings ?? new ChangeTrackingList(), - apiProfiles ?? new ChangeTrackingList(), - capabilities, - properties ?? new ChangeTrackingDictionary(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ResourceType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" resourceType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ResourceType)) - { - builder.Append(" resourceType: "); - if (ResourceType.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ResourceType}'''"); - } - else - { - builder.AppendLine($"'{ResourceType}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Locations), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" locations: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Locations)) - { - if (Locations.Any()) - { - builder.Append(" locations: "); - builder.AppendLine("["); - foreach (var item in Locations) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(LocationMappings), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" locationMappings: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(LocationMappings)) - { - if (LocationMappings.Any()) - { - builder.Append(" locationMappings: "); - builder.AppendLine("["); - foreach (var item in LocationMappings) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " locationMappings: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Aliases), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" aliases: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Aliases)) - { - if (Aliases.Any()) - { - builder.Append(" aliases: "); - builder.AppendLine("["); - foreach (var item in Aliases) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " aliases: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ApiVersions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" apiVersions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ApiVersions)) - { - if (ApiVersions.Any()) - { - builder.Append(" apiVersions: "); - builder.AppendLine("["); - foreach (var item in ApiVersions) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DefaultApiVersion), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" defaultApiVersion: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DefaultApiVersion)) - { - builder.Append(" defaultApiVersion: "); - if (DefaultApiVersion.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DefaultApiVersion}'''"); - } - else - { - builder.AppendLine($"'{DefaultApiVersion}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ZoneMappings), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" zoneMappings: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ZoneMappings)) - { - if (ZoneMappings.Any()) - { - builder.Append(" zoneMappings: "); - builder.AppendLine("["); - foreach (var item in ZoneMappings) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " zoneMappings: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ApiProfiles), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" apiProfiles: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ApiProfiles)) - { - if (ApiProfiles.Any()) - { - builder.Append(" apiProfiles: "); - builder.AppendLine("["); - foreach (var item in ApiProfiles) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " apiProfiles: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Capabilities), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" capabilities: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Capabilities)) - { - builder.Append(" capabilities: "); - if (Capabilities.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Capabilities}'''"); - } - else - { - builder.AppendLine($"'{Capabilities}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Properties), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" properties: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Properties)) - { - if (Properties.Any()) - { - builder.Append(" properties: "); - builder.AppendLine("{"); - foreach (var item in Properties) - { - builder.Append($" '{item.Key}': "); - if (item.Value == null) - { - builder.Append("null"); - continue; - } - if (item.Value.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{item.Value}'''"); - } - else - { - builder.AppendLine($"'{item.Value}'"); - } - } - builder.AppendLine(" }"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ProviderResourceType)} does not support writing '{options.Format}' format."); - } - } - - ProviderResourceType IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeProviderResourceType(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ProviderResourceType)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceType.cs deleted file mode 100644 index 64234b3ba9..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceType.cs +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Resource type managed by the resource provider. - public partial class ProviderResourceType - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ProviderResourceType() - { - Locations = new ChangeTrackingList(); - LocationMappings = new ChangeTrackingList(); - Aliases = new ChangeTrackingList(); - ApiVersions = new ChangeTrackingList(); - ZoneMappings = new ChangeTrackingList(); - ApiProfiles = new ChangeTrackingList(); - Properties = new ChangeTrackingDictionary(); - } - - /// Initializes a new instance of . - /// The resource type. - /// The collection of locations where this resource type can be created. - /// The location mappings that are supported by this resource type. - /// The aliases that are supported by this resource type. - /// The API version. - /// The default API version. - /// - /// The API profiles for the resource provider. - /// The additional capabilities offered by this resource type. - /// The properties. - /// Keeps track of any properties unknown to the library. - internal ProviderResourceType(string resourceType, IReadOnlyList locations, IReadOnlyList locationMappings, IReadOnlyList aliases, IReadOnlyList apiVersions, string defaultApiVersion, IReadOnlyList zoneMappings, IReadOnlyList apiProfiles, string capabilities, IReadOnlyDictionary properties, IDictionary serializedAdditionalRawData) - { - ResourceType = resourceType; - Locations = locations; - LocationMappings = locationMappings; - Aliases = aliases; - ApiVersions = apiVersions; - DefaultApiVersion = defaultApiVersion; - ZoneMappings = zoneMappings; - ApiProfiles = apiProfiles; - Capabilities = capabilities; - Properties = properties; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The resource type. - [WirePath("resourceType")] - public string ResourceType { get; } - /// The collection of locations where this resource type can be created. - [WirePath("locations")] - public IReadOnlyList Locations { get; } - /// The location mappings that are supported by this resource type. - [WirePath("locationMappings")] - public IReadOnlyList LocationMappings { get; } - /// The aliases that are supported by this resource type. - [WirePath("aliases")] - public IReadOnlyList Aliases { get; } - /// The API version. - [WirePath("apiVersions")] - public IReadOnlyList ApiVersions { get; } - /// The default API version. - [WirePath("defaultApiVersion")] - public string DefaultApiVersion { get; } - /// Gets the zone mappings. - [WirePath("zoneMappings")] - public IReadOnlyList ZoneMappings { get; } - /// The API profiles for the resource provider. - [WirePath("apiProfiles")] - public IReadOnlyList ApiProfiles { get; } - /// The additional capabilities offered by this resource type. - [WirePath("capabilities")] - public string Capabilities { get; } - /// The properties. - [WirePath("properties")] - public IReadOnlyDictionary Properties { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceTypeListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceTypeListResult.Serialization.cs deleted file mode 100644 index 0b206fd01f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceTypeListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class ProviderResourceTypeListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderResourceTypeListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ProviderResourceTypeListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderResourceTypeListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeProviderResourceTypeListResult(document.RootElement, options); - } - - internal static ProviderResourceTypeListResult DeserializeProviderResourceTypeListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ProviderResourceType.DeserializeProviderResourceType(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ProviderResourceTypeListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ProviderResourceTypeListResult)} does not support writing '{options.Format}' format."); - } - } - - ProviderResourceTypeListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeProviderResourceTypeListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ProviderResourceTypeListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceTypeListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceTypeListResult.cs deleted file mode 100644 index e58854a89d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceTypeListResult.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of resource types of a resource provider. - internal partial class ProviderResourceTypeListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ProviderResourceTypeListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of resource types. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal ProviderResourceTypeListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of resource types. - [WirePath("value")] - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - [WirePath("nextLink")] - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/RegionCategory.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/RegionCategory.cs deleted file mode 100644 index 4f94df158a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/RegionCategory.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The category of the region. - public readonly partial struct RegionCategory : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public RegionCategory(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string RecommendedValue = "Recommended"; - private const string ExtendedValue = "Extended"; - private const string OtherValue = "Other"; - - /// Recommended. - public static RegionCategory Recommended { get; } = new RegionCategory(RecommendedValue); - /// Extended. - public static RegionCategory Extended { get; } = new RegionCategory(ExtendedValue); - /// Other. - public static RegionCategory Other { get; } = new RegionCategory(OtherValue); - /// Determines if two values are the same. - public static bool operator ==(RegionCategory left, RegionCategory right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(RegionCategory left, RegionCategory right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator RegionCategory(string value) => new RegionCategory(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is RegionCategory other && Equals(other); - /// - public bool Equals(RegionCategory other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/RegionType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/RegionType.cs deleted file mode 100644 index b78f1316be..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/RegionType.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The type of the region. - public readonly partial struct RegionType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public RegionType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string PhysicalValue = "Physical"; - private const string LogicalValue = "Logical"; - - /// Physical. - public static RegionType Physical { get; } = new RegionType(PhysicalValue); - /// Logical. - public static RegionType Logical { get; } = new RegionType(LogicalValue); - /// Determines if two values are the same. - public static bool operator ==(RegionType left, RegionType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(RegionType left, RegionType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator RegionType(string value) => new RegionType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is RegionType other && Equals(other); - /// - public bool Equals(RegionType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupExportResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupExportResult.Serialization.cs deleted file mode 100644 index c6b32ddbe6..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupExportResult.Serialization.cs +++ /dev/null @@ -1,203 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceGroupExportResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupExportResult)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Template)) - { - writer.WritePropertyName("template"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(Template); -#else - using (JsonDocument document = JsonDocument.Parse(Template, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - if (Optional.IsDefined(Error)) - { - writer.WritePropertyName("error"u8); - JsonSerializer.Serialize(writer, Error, ResourceManagerJsonContext.Default.ResponseError); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ResourceGroupExportResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupExportResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceGroupExportResult(document.RootElement, options); - } - - internal static ResourceGroupExportResult DeserializeResourceGroupExportResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - BinaryData template = default; - ResponseError error = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("template"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - template = BinaryData.FromString(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("error"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - error = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.ResponseError); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceGroupExportResult(template, error, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Template), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" template: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Template)) - { - builder.Append(" template: "); - builder.AppendLine($"'{Template.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Error), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" error: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Error)) - { - builder.Append(" error: "); - BicepSerializationHelpers.AppendChildObject(builder, Error, options, 2, false, " error: "); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceGroupExportResult)} does not support writing '{options.Format}' format."); - } - } - - ResourceGroupExportResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceGroupExportResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceGroupExportResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupExportResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupExportResult.cs deleted file mode 100644 index b6a5fd70bd..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupExportResult.cs +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Resource group export result. - public partial class ResourceGroupExportResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceGroupExportResult() - { - } - - /// Initializes a new instance of . - /// The template content. - /// The template export error. - /// Keeps track of any properties unknown to the library. - internal ResourceGroupExportResult(BinaryData template, ResponseError error, IDictionary serializedAdditionalRawData) - { - Template = template; - Error = error; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// - /// The template content. - /// - /// To assign an object to this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("template")] - public BinaryData Template { get; } - /// The template export error. - [WirePath("error")] - public ResponseError Error { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupListResult.Serialization.cs deleted file mode 100644 index d618fa828a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class ResourceGroupListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ResourceGroupListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceGroupListResult(document.RootElement, options); - } - - internal static ResourceGroupListResult DeserializeResourceGroupListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ResourceGroupData.DeserializeResourceGroupData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceGroupListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceGroupListResult)} does not support writing '{options.Format}' format."); - } - } - - ResourceGroupListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceGroupListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceGroupListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupListResult.cs deleted file mode 100644 index aad563b999..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of resource groups. - internal partial class ResourceGroupListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceGroupListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of resource groups. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal ResourceGroupListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of resource groups. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupPatch.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupPatch.Serialization.cs deleted file mode 100644 index c8ee490aac..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupPatch.Serialization.cs +++ /dev/null @@ -1,181 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceGroupPatch : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupPatch)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(Properties)) - { - writer.WritePropertyName("properties"u8); - writer.WriteObjectValue(Properties, options); - } - if (Optional.IsDefined(ManagedBy)) - { - writer.WritePropertyName("managedBy"u8); - writer.WriteStringValue(ManagedBy); - } - if (Optional.IsCollectionDefined(Tags)) - { - writer.WritePropertyName("tags"u8); - writer.WriteStartObject(); - foreach (var item in Tags) - { - writer.WritePropertyName(item.Key); - writer.WriteStringValue(item.Value); - } - writer.WriteEndObject(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ResourceGroupPatch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupPatch)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceGroupPatch(document.RootElement, options); - } - - internal static ResourceGroupPatch DeserializeResourceGroupPatch(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - ResourceGroupProperties properties = default; - string managedBy = default; - IDictionary tags = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - properties = ResourceGroupProperties.DeserializeResourceGroupProperties(property.Value, options); - continue; - } - if (property.NameEquals("managedBy"u8)) - { - managedBy = property.Value.GetString(); - continue; - } - if (property.NameEquals("tags"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - tags = dictionary; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceGroupPatch(name, properties, managedBy, tags ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ResourceGroupPatch)} does not support writing '{options.Format}' format."); - } - } - - ResourceGroupPatch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceGroupPatch(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceGroupPatch)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupPatch.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupPatch.cs deleted file mode 100644 index b10e558b03..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupPatch.cs +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Resource group information. - public partial class ResourceGroupPatch - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ResourceGroupPatch() - { - Tags = new ChangeTrackingDictionary(); - } - - /// Initializes a new instance of . - /// The name of the resource group. - /// The resource group properties. - /// The ID of the resource that manages this resource group. - /// The tags attached to the resource group. - /// Keeps track of any properties unknown to the library. - internal ResourceGroupPatch(string name, ResourceGroupProperties properties, string managedBy, IDictionary tags, IDictionary serializedAdditionalRawData) - { - Name = name; - Properties = properties; - ManagedBy = managedBy; - Tags = tags; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The name of the resource group. - [WirePath("name")] - public string Name { get; set; } - /// The resource group properties. - internal ResourceGroupProperties Properties { get; set; } - /// The provisioning state. - [WirePath("properties.provisioningState")] - public string ResourceGroupProvisioningState - { - get => Properties is null ? default : Properties.ProvisioningState; - } - - /// The ID of the resource that manages this resource group. - [WirePath("managedBy")] - public string ManagedBy { get; set; } - /// The tags attached to the resource group. - [WirePath("tags")] - public IDictionary Tags { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupProperties.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupProperties.Serialization.cs deleted file mode 100644 index c364b7d06c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupProperties.Serialization.cs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class ResourceGroupProperties : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupProperties)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(ProvisioningState)) - { - writer.WritePropertyName("provisioningState"u8); - writer.WriteStringValue(ProvisioningState); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ResourceGroupProperties IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupProperties)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceGroupProperties(document.RootElement, options); - } - - internal static ResourceGroupProperties DeserializeResourceGroupProperties(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string provisioningState = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("provisioningState"u8)) - { - provisioningState = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceGroupProperties(provisioningState, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ProvisioningState), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" provisioningState: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ProvisioningState)) - { - builder.Append(" provisioningState: "); - if (ProvisioningState.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ProvisioningState}'''"); - } - else - { - builder.AppendLine($"'{ProvisioningState}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceGroupProperties)} does not support writing '{options.Format}' format."); - } - } - - ResourceGroupProperties IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceGroupProperties(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceGroupProperties)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupProperties.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupProperties.cs deleted file mode 100644 index b62fad0a7f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupProperties.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The resource group properties. - internal partial class ResourceGroupProperties - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ResourceGroupProperties() - { - } - - /// Initializes a new instance of . - /// The provisioning state. - /// Keeps track of any properties unknown to the library. - internal ResourceGroupProperties(string provisioningState, IDictionary serializedAdditionalRawData) - { - ProvisioningState = provisioningState; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The provisioning state. - [WirePath("provisioningState")] - public string ProvisioningState { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceListResult.Serialization.cs deleted file mode 100644 index 1c5d2308b6..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class ResourceListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ResourceListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceListResult(document.RootElement, options); - } - - internal static ResourceListResult DeserializeResourceListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(GenericResourceData.DeserializeGenericResourceData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceListResult)} does not support writing '{options.Format}' format."); - } - } - - ResourceListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceListResult.cs deleted file mode 100644 index 6d1d19e150..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of resource groups. - internal partial class ResourceListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of resources. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal ResourceListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of resources. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationContent.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationContent.Serialization.cs deleted file mode 100644 index 928c6e4959..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationContent.Serialization.cs +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceNameValidationContent : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceNameValidationContent)} does not support writing '{format}' format."); - } - - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ResourceType); - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ResourceNameValidationContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceNameValidationContent)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceNameValidationContent(document.RootElement, options); - } - - internal static ResourceNameValidationContent DeserializeResourceNameValidationContent(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - ResourceType type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceNameValidationContent(name, type, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ResourceNameValidationContent)} does not support writing '{options.Format}' format."); - } - } - - ResourceNameValidationContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceNameValidationContent(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceNameValidationContent)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationContent.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationContent.cs deleted file mode 100644 index e3886a6c2f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationContent.cs +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Name and Type of the Resource. - public partial class ResourceNameValidationContent - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// Name of the resource. - /// The type of the resource. - /// is null. - public ResourceNameValidationContent(string name, ResourceType resourceType) - { - Argument.AssertNotNull(name, nameof(name)); - - Name = name; - ResourceType = resourceType; - } - - /// Initializes a new instance of . - /// Name of the resource. - /// The type of the resource. - /// Keeps track of any properties unknown to the library. - internal ResourceNameValidationContent(string name, ResourceType resourceType, IDictionary serializedAdditionalRawData) - { - Name = name; - ResourceType = resourceType; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal ResourceNameValidationContent() - { - } - - /// Name of the resource. - [WirePath("name")] - public string Name { get; } - /// The type of the resource. - [WirePath("type")] - public ResourceType ResourceType { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationResult.Serialization.cs deleted file mode 100644 index 96c45266ff..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationResult.Serialization.cs +++ /dev/null @@ -1,230 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceNameValidationResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceNameValidationResult)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(ResourceType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ResourceType.Value); - } - if (Optional.IsDefined(Status)) - { - writer.WritePropertyName("status"u8); - writer.WriteStringValue(Status.Value.ToString()); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ResourceNameValidationResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceNameValidationResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceNameValidationResult(document.RootElement, options); - } - - internal static ResourceNameValidationResult DeserializeResourceNameValidationResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - ResourceType? type = default; - ResourceNameValidationStatus? status = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("status"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - status = new ResourceNameValidationStatus(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceNameValidationResult(name, type, status, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ResourceType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" type: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ResourceType)) - { - builder.Append(" type: "); - builder.AppendLine($"'{ResourceType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Status), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" status: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Status)) - { - builder.Append(" status: "); - builder.AppendLine($"'{Status.Value.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceNameValidationResult)} does not support writing '{options.Format}' format."); - } - } - - ResourceNameValidationResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceNameValidationResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceNameValidationResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationResult.cs deleted file mode 100644 index 7e0501f862..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationResult.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Resource Name valid if not a reserved word, does not contain a reserved word and does not start with a reserved word. - public partial class ResourceNameValidationResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceNameValidationResult() - { - } - - /// Initializes a new instance of . - /// Name of Resource. - /// Type of Resource. - /// Is the resource name Allowed or Reserved. - /// Keeps track of any properties unknown to the library. - internal ResourceNameValidationResult(string name, ResourceType? resourceType, ResourceNameValidationStatus? status, IDictionary serializedAdditionalRawData) - { - Name = name; - ResourceType = resourceType; - Status = status; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Name of Resource. - [WirePath("name")] - public string Name { get; } - /// Type of Resource. - [WirePath("type")] - public ResourceType? ResourceType { get; } - /// Is the resource name Allowed or Reserved. - [WirePath("status")] - public ResourceNameValidationStatus? Status { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationStatus.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationStatus.cs deleted file mode 100644 index 78a1b378f1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationStatus.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Is the resource name Allowed or Reserved. - public readonly partial struct ResourceNameValidationStatus : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ResourceNameValidationStatus(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string AllowedValue = "Allowed"; - private const string ReservedValue = "Reserved"; - - /// Allowed. - public static ResourceNameValidationStatus Allowed { get; } = new ResourceNameValidationStatus(AllowedValue); - /// Reserved. - public static ResourceNameValidationStatus Reserved { get; } = new ResourceNameValidationStatus(ReservedValue); - /// Determines if two values are the same. - public static bool operator ==(ResourceNameValidationStatus left, ResourceNameValidationStatus right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ResourceNameValidationStatus left, ResourceNameValidationStatus right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ResourceNameValidationStatus(string value) => new ResourceNameValidationStatus(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ResourceNameValidationStatus other && Equals(other); - /// - public bool Equals(ResourceNameValidationStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceProviderListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceProviderListResult.Serialization.cs deleted file mode 100644 index dd4d71e28e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceProviderListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class ResourceProviderListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceProviderListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ResourceProviderListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceProviderListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceProviderListResult(document.RootElement, options); - } - - internal static ResourceProviderListResult DeserializeResourceProviderListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ResourceProviderData.DeserializeResourceProviderData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceProviderListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceProviderListResult)} does not support writing '{options.Format}' format."); - } - } - - ResourceProviderListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceProviderListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceProviderListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceProviderListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceProviderListResult.cs deleted file mode 100644 index 1049d3073b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceProviderListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of resource providers. - internal partial class ResourceProviderListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceProviderListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of resource providers. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal ResourceProviderListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of resource providers. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelector.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelector.Serialization.cs deleted file mode 100644 index 6d5ec1b795..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelector.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceSelector : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceSelector)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsCollectionDefined(Selectors)) - { - writer.WritePropertyName("selectors"u8); - writer.WriteStartArray(); - foreach (var item in Selectors) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ResourceSelector IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceSelector)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceSelector(document.RootElement, options); - } - - internal static ResourceSelector DeserializeResourceSelector(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - IList selectors = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("selectors"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ResourceSelectorExpression.DeserializeResourceSelectorExpression(item, options)); - } - selectors = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceSelector(name, selectors ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Selectors), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" selectors: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Selectors)) - { - if (Selectors.Any()) - { - builder.Append(" selectors: "); - builder.AppendLine("["); - foreach (var item in Selectors) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " selectors: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceSelector)} does not support writing '{options.Format}' format."); - } - } - - ResourceSelector IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceSelector(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceSelector)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelector.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelector.cs deleted file mode 100644 index e85c7541cb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelector.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The resource selector to filter policies by resource properties. - public partial class ResourceSelector - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ResourceSelector() - { - Selectors = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The name of the resource selector. - /// The list of the selector expressions. - /// Keeps track of any properties unknown to the library. - internal ResourceSelector(string name, IList selectors, IDictionary serializedAdditionalRawData) - { - Name = name; - Selectors = selectors; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The name of the resource selector. - [WirePath("name")] - public string Name { get; set; } - /// The list of the selector expressions. - [WirePath("selectors")] - public IList Selectors { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorExpression.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorExpression.Serialization.cs deleted file mode 100644 index 4deb3a5e27..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorExpression.Serialization.cs +++ /dev/null @@ -1,289 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceSelectorExpression : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceSelectorExpression)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Kind)) - { - writer.WritePropertyName("kind"u8); - writer.WriteStringValue(Kind.Value.ToString()); - } - if (Optional.IsCollectionDefined(In)) - { - writer.WritePropertyName("in"u8); - writer.WriteStartArray(); - foreach (var item in In) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(NotIn)) - { - writer.WritePropertyName("notIn"u8); - writer.WriteStartArray(); - foreach (var item in NotIn) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ResourceSelectorExpression IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceSelectorExpression)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceSelectorExpression(document.RootElement, options); - } - - internal static ResourceSelectorExpression DeserializeResourceSelectorExpression(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceSelectorKind? kind = default; - IList @in = default; - IList notIn = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("kind"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - kind = new ResourceSelectorKind(property.Value.GetString()); - continue; - } - if (property.NameEquals("in"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - @in = array; - continue; - } - if (property.NameEquals("notIn"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - notIn = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceSelectorExpression(kind, @in ?? new ChangeTrackingList(), notIn ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Kind), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" kind: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Kind)) - { - builder.Append(" kind: "); - builder.AppendLine($"'{Kind.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(In), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" in: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(In)) - { - if (In.Any()) - { - builder.Append(" in: "); - builder.AppendLine("["); - foreach (var item in In) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NotIn), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" notIn: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(NotIn)) - { - if (NotIn.Any()) - { - builder.Append(" notIn: "); - builder.AppendLine("["); - foreach (var item in NotIn) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceSelectorExpression)} does not support writing '{options.Format}' format."); - } - } - - ResourceSelectorExpression IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceSelectorExpression(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceSelectorExpression)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorExpression.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorExpression.cs deleted file mode 100644 index c10dad80a6..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorExpression.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The selector expression. - public partial class ResourceSelectorExpression - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ResourceSelectorExpression() - { - In = new ChangeTrackingList(); - NotIn = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The selector kind. - /// The list of values to filter in. - /// The list of values to filter out. - /// Keeps track of any properties unknown to the library. - internal ResourceSelectorExpression(ResourceSelectorKind? kind, IList @in, IList notIn, IDictionary serializedAdditionalRawData) - { - Kind = kind; - In = @in; - NotIn = notIn; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The selector kind. - [WirePath("kind")] - public ResourceSelectorKind? Kind { get; set; } - /// The list of values to filter in. - [WirePath("in")] - public IList In { get; } - /// The list of values to filter out. - [WirePath("notIn")] - public IList NotIn { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorKind.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorKind.cs deleted file mode 100644 index bed65e9a77..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorKind.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The selector kind. - public readonly partial struct ResourceSelectorKind : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ResourceSelectorKind(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string ResourceLocationValue = "resourceLocation"; - private const string ResourceTypeValue = "resourceType"; - private const string ResourceWithoutLocationValue = "resourceWithoutLocation"; - private const string PolicyDefinitionReferenceIdValue = "policyDefinitionReferenceId"; - - /// The selector kind to filter policies by the resource location. - public static ResourceSelectorKind ResourceLocation { get; } = new ResourceSelectorKind(ResourceLocationValue); - /// The selector kind to filter policies by the resource type. - public static ResourceSelectorKind ResourceType { get; } = new ResourceSelectorKind(ResourceTypeValue); - /// The selector kind to filter policies by the resource without location. - public static ResourceSelectorKind ResourceWithoutLocation { get; } = new ResourceSelectorKind(ResourceWithoutLocationValue); - /// The selector kind to filter policies by the policy definition reference ID. - public static ResourceSelectorKind PolicyDefinitionReferenceId { get; } = new ResourceSelectorKind(PolicyDefinitionReferenceIdValue); - /// Determines if two values are the same. - public static bool operator ==(ResourceSelectorKind left, ResourceSelectorKind right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ResourceSelectorKind left, ResourceSelectorKind right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ResourceSelectorKind(string value) => new ResourceSelectorKind(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ResourceSelectorKind other && Equals(other); - /// - public bool Equals(ResourceSelectorKind other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAlias.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAlias.Serialization.cs deleted file mode 100644 index 74e70a3ebd..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAlias.Serialization.cs +++ /dev/null @@ -1,350 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceTypeAlias : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAlias)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsCollectionDefined(Paths)) - { - writer.WritePropertyName("paths"u8); - writer.WriteStartArray(); - foreach (var item in Paths) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(AliasType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(AliasType.Value.ToSerialString()); - } - if (Optional.IsDefined(DefaultPath)) - { - writer.WritePropertyName("defaultPath"u8); - writer.WriteStringValue(DefaultPath); - } - if (Optional.IsDefined(DefaultPattern)) - { - writer.WritePropertyName("defaultPattern"u8); - writer.WriteObjectValue(DefaultPattern, options); - } - if (options.Format != "W" && Optional.IsDefined(DefaultMetadata)) - { - writer.WritePropertyName("defaultMetadata"u8); - writer.WriteObjectValue(DefaultMetadata, options); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ResourceTypeAlias IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAlias)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceTypeAlias(document.RootElement, options); - } - - internal static ResourceTypeAlias DeserializeResourceTypeAlias(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - IReadOnlyList paths = default; - ResourceTypeAliasType? type = default; - string defaultPath = default; - ResourceTypeAliasPattern defaultPattern = default; - ResourceTypeAliasPathMetadata defaultMetadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("paths"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ResourceTypeAliasPath.DeserializeResourceTypeAliasPath(item, options)); - } - paths = array; - continue; - } - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = property.Value.GetString().ToResourceTypeAliasType(); - continue; - } - if (property.NameEquals("defaultPath"u8)) - { - defaultPath = property.Value.GetString(); - continue; - } - if (property.NameEquals("defaultPattern"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - defaultPattern = ResourceTypeAliasPattern.DeserializeResourceTypeAliasPattern(property.Value, options); - continue; - } - if (property.NameEquals("defaultMetadata"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - defaultMetadata = ResourceTypeAliasPathMetadata.DeserializeResourceTypeAliasPathMetadata(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceTypeAlias( - name, - paths ?? new ChangeTrackingList(), - type, - defaultPath, - defaultPattern, - defaultMetadata, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Paths), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" paths: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Paths)) - { - if (Paths.Any()) - { - builder.Append(" paths: "); - builder.AppendLine("["); - foreach (var item in Paths) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " paths: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(AliasType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" type: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(AliasType)) - { - builder.Append(" type: "); - builder.AppendLine($"'{AliasType.Value.ToSerialString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DefaultPath), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" defaultPath: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DefaultPath)) - { - builder.Append(" defaultPath: "); - if (DefaultPath.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DefaultPath}'''"); - } - else - { - builder.AppendLine($"'{DefaultPath}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DefaultPattern), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" defaultPattern: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DefaultPattern)) - { - builder.Append(" defaultPattern: "); - BicepSerializationHelpers.AppendChildObject(builder, DefaultPattern, options, 2, false, " defaultPattern: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DefaultMetadata), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" defaultMetadata: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DefaultMetadata)) - { - builder.Append(" defaultMetadata: "); - BicepSerializationHelpers.AppendChildObject(builder, DefaultMetadata, options, 2, false, " defaultMetadata: "); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceTypeAlias)} does not support writing '{options.Format}' format."); - } - } - - ResourceTypeAlias IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceTypeAlias(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceTypeAlias)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAlias.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAlias.cs deleted file mode 100644 index 26ac43a913..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAlias.cs +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The alias type. - public partial class ResourceTypeAlias - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceTypeAlias() - { - Paths = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The alias name. - /// The paths for an alias. - /// The type of the alias. - /// The default path for an alias. - /// The default pattern for an alias. - /// The default alias path metadata. Applies to the default path and to any alias path that doesn't have metadata. - /// Keeps track of any properties unknown to the library. - internal ResourceTypeAlias(string name, IReadOnlyList paths, ResourceTypeAliasType? aliasType, string defaultPath, ResourceTypeAliasPattern defaultPattern, ResourceTypeAliasPathMetadata defaultMetadata, IDictionary serializedAdditionalRawData) - { - Name = name; - Paths = paths; - AliasType = aliasType; - DefaultPath = defaultPath; - DefaultPattern = defaultPattern; - DefaultMetadata = defaultMetadata; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The alias name. - [WirePath("name")] - public string Name { get; } - /// The paths for an alias. - [WirePath("paths")] - public IReadOnlyList Paths { get; } - /// The type of the alias. - [WirePath("type")] - public ResourceTypeAliasType? AliasType { get; } - /// The default path for an alias. - [WirePath("defaultPath")] - public string DefaultPath { get; } - /// The default pattern for an alias. - [WirePath("defaultPattern")] - public ResourceTypeAliasPattern DefaultPattern { get; } - /// The default alias path metadata. Applies to the default path and to any alias path that doesn't have metadata. - [WirePath("defaultMetadata")] - public ResourceTypeAliasPathMetadata DefaultMetadata { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPath.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPath.Serialization.cs deleted file mode 100644 index f98d9c2e88..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPath.Serialization.cs +++ /dev/null @@ -1,292 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceTypeAliasPath : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAliasPath)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Path)) - { - writer.WritePropertyName("path"u8); - writer.WriteStringValue(Path); - } - if (Optional.IsCollectionDefined(ApiVersions)) - { - writer.WritePropertyName("apiVersions"u8); - writer.WriteStartArray(); - foreach (var item in ApiVersions) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(Pattern)) - { - writer.WritePropertyName("pattern"u8); - writer.WriteObjectValue(Pattern, options); - } - if (options.Format != "W" && Optional.IsDefined(Metadata)) - { - writer.WritePropertyName("metadata"u8); - writer.WriteObjectValue(Metadata, options); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ResourceTypeAliasPath IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAliasPath)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceTypeAliasPath(document.RootElement, options); - } - - internal static ResourceTypeAliasPath DeserializeResourceTypeAliasPath(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string path = default; - IReadOnlyList apiVersions = default; - ResourceTypeAliasPattern pattern = default; - ResourceTypeAliasPathMetadata metadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("path"u8)) - { - path = property.Value.GetString(); - continue; - } - if (property.NameEquals("apiVersions"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - apiVersions = array; - continue; - } - if (property.NameEquals("pattern"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - pattern = ResourceTypeAliasPattern.DeserializeResourceTypeAliasPattern(property.Value, options); - continue; - } - if (property.NameEquals("metadata"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - metadata = ResourceTypeAliasPathMetadata.DeserializeResourceTypeAliasPathMetadata(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceTypeAliasPath(path, apiVersions ?? new ChangeTrackingList(), pattern, metadata, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Path), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" path: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Path)) - { - builder.Append(" path: "); - if (Path.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Path}'''"); - } - else - { - builder.AppendLine($"'{Path}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ApiVersions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" apiVersions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ApiVersions)) - { - if (ApiVersions.Any()) - { - builder.Append(" apiVersions: "); - builder.AppendLine("["); - foreach (var item in ApiVersions) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Pattern), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" pattern: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Pattern)) - { - builder.Append(" pattern: "); - BicepSerializationHelpers.AppendChildObject(builder, Pattern, options, 2, false, " pattern: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Metadata), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" metadata: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Metadata)) - { - builder.Append(" metadata: "); - BicepSerializationHelpers.AppendChildObject(builder, Metadata, options, 2, false, " metadata: "); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceTypeAliasPath)} does not support writing '{options.Format}' format."); - } - } - - ResourceTypeAliasPath IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceTypeAliasPath(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceTypeAliasPath)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPath.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPath.cs deleted file mode 100644 index acd74e09e7..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPath.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The type of the paths for alias. - public partial class ResourceTypeAliasPath - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceTypeAliasPath() - { - ApiVersions = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The path of an alias. - /// The API versions. - /// The pattern for an alias path. - /// The metadata of the alias path. If missing, fall back to the default metadata of the alias. - /// Keeps track of any properties unknown to the library. - internal ResourceTypeAliasPath(string path, IReadOnlyList apiVersions, ResourceTypeAliasPattern pattern, ResourceTypeAliasPathMetadata metadata, IDictionary serializedAdditionalRawData) - { - Path = path; - ApiVersions = apiVersions; - Pattern = pattern; - Metadata = metadata; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The path of an alias. - [WirePath("path")] - public string Path { get; } - /// The API versions. - [WirePath("apiVersions")] - public IReadOnlyList ApiVersions { get; } - /// The pattern for an alias path. - [WirePath("pattern")] - public ResourceTypeAliasPattern Pattern { get; } - /// The metadata of the alias path. If missing, fall back to the default metadata of the alias. - [WirePath("metadata")] - public ResourceTypeAliasPathMetadata Metadata { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathAttributes.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathAttributes.cs deleted file mode 100644 index 217d95e60d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathAttributes.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The attributes of the token that the alias path is referring to. - public readonly partial struct ResourceTypeAliasPathAttributes : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ResourceTypeAliasPathAttributes(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string NoneValue = "None"; - private const string ModifiableValue = "Modifiable"; - - /// The token that the alias path is referring to has no attributes. - public static ResourceTypeAliasPathAttributes None { get; } = new ResourceTypeAliasPathAttributes(NoneValue); - /// The token that the alias path is referring to is modifiable by policies with 'modify' effect. - public static ResourceTypeAliasPathAttributes Modifiable { get; } = new ResourceTypeAliasPathAttributes(ModifiableValue); - /// Determines if two values are the same. - public static bool operator ==(ResourceTypeAliasPathAttributes left, ResourceTypeAliasPathAttributes right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ResourceTypeAliasPathAttributes left, ResourceTypeAliasPathAttributes right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ResourceTypeAliasPathAttributes(string value) => new ResourceTypeAliasPathAttributes(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ResourceTypeAliasPathAttributes other && Equals(other); - /// - public bool Equals(ResourceTypeAliasPathAttributes other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathMetadata.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathMetadata.Serialization.cs deleted file mode 100644 index 6ba6a18823..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathMetadata.Serialization.cs +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceTypeAliasPathMetadata : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAliasPathMetadata)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(TokenType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(TokenType.Value.ToString()); - } - if (options.Format != "W" && Optional.IsDefined(Attributes)) - { - writer.WritePropertyName("attributes"u8); - writer.WriteStringValue(Attributes.Value.ToString()); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ResourceTypeAliasPathMetadata IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAliasPathMetadata)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceTypeAliasPathMetadata(document.RootElement, options); - } - - internal static ResourceTypeAliasPathMetadata DeserializeResourceTypeAliasPathMetadata(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceTypeAliasPathTokenType? type = default; - ResourceTypeAliasPathAttributes? attributes = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = new ResourceTypeAliasPathTokenType(property.Value.GetString()); - continue; - } - if (property.NameEquals("attributes"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - attributes = new ResourceTypeAliasPathAttributes(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceTypeAliasPathMetadata(type, attributes, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TokenType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" type: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TokenType)) - { - builder.Append(" type: "); - builder.AppendLine($"'{TokenType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Attributes), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" attributes: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Attributes)) - { - builder.Append(" attributes: "); - builder.AppendLine($"'{Attributes.Value.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceTypeAliasPathMetadata)} does not support writing '{options.Format}' format."); - } - } - - ResourceTypeAliasPathMetadata IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceTypeAliasPathMetadata(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceTypeAliasPathMetadata)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathMetadata.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathMetadata.cs deleted file mode 100644 index 1a4b48937b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathMetadata.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The ResourceTypeAliasPathMetadata. - public partial class ResourceTypeAliasPathMetadata - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceTypeAliasPathMetadata() - { - } - - /// Initializes a new instance of . - /// The type of the token that the alias path is referring to. - /// The attributes of the token that the alias path is referring to. - /// Keeps track of any properties unknown to the library. - internal ResourceTypeAliasPathMetadata(ResourceTypeAliasPathTokenType? tokenType, ResourceTypeAliasPathAttributes? attributes, IDictionary serializedAdditionalRawData) - { - TokenType = tokenType; - Attributes = attributes; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The type of the token that the alias path is referring to. - [WirePath("type")] - public ResourceTypeAliasPathTokenType? TokenType { get; } - /// The attributes of the token that the alias path is referring to. - [WirePath("attributes")] - public ResourceTypeAliasPathAttributes? Attributes { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathTokenType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathTokenType.cs deleted file mode 100644 index 98fd72b001..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathTokenType.cs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The type of the token that the alias path is referring to. - public readonly partial struct ResourceTypeAliasPathTokenType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ResourceTypeAliasPathTokenType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string NotSpecifiedValue = "NotSpecified"; - private const string AnyValue = "Any"; - private const string StringValue = "String"; - private const string ObjectValue = "Object"; - private const string ArrayValue = "Array"; - private const string IntegerValue = "Integer"; - private const string NumberValue = "Number"; - private const string BooleanValue = "Boolean"; - - /// The token type is not specified. - public static ResourceTypeAliasPathTokenType NotSpecified { get; } = new ResourceTypeAliasPathTokenType(NotSpecifiedValue); - /// The token type can be anything. - public static ResourceTypeAliasPathTokenType Any { get; } = new ResourceTypeAliasPathTokenType(AnyValue); - /// The token type is string. - public static ResourceTypeAliasPathTokenType String { get; } = new ResourceTypeAliasPathTokenType(StringValue); - /// The token type is object. - public static ResourceTypeAliasPathTokenType Object { get; } = new ResourceTypeAliasPathTokenType(ObjectValue); - /// The token type is array. - public static ResourceTypeAliasPathTokenType Array { get; } = new ResourceTypeAliasPathTokenType(ArrayValue); - /// The token type is integer. - public static ResourceTypeAliasPathTokenType Integer { get; } = new ResourceTypeAliasPathTokenType(IntegerValue); - /// The token type is number. - public static ResourceTypeAliasPathTokenType Number { get; } = new ResourceTypeAliasPathTokenType(NumberValue); - /// The token type is boolean. - public static ResourceTypeAliasPathTokenType Boolean { get; } = new ResourceTypeAliasPathTokenType(BooleanValue); - /// Determines if two values are the same. - public static bool operator ==(ResourceTypeAliasPathTokenType left, ResourceTypeAliasPathTokenType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ResourceTypeAliasPathTokenType left, ResourceTypeAliasPathTokenType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ResourceTypeAliasPathTokenType(string value) => new ResourceTypeAliasPathTokenType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ResourceTypeAliasPathTokenType other && Equals(other); - /// - public bool Equals(ResourceTypeAliasPathTokenType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPattern.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPattern.Serialization.cs deleted file mode 100644 index 1d5a9f69aa..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPattern.Serialization.cs +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceTypeAliasPattern : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAliasPattern)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Phrase)) - { - writer.WritePropertyName("phrase"u8); - writer.WriteStringValue(Phrase); - } - if (Optional.IsDefined(Variable)) - { - writer.WritePropertyName("variable"u8); - writer.WriteStringValue(Variable); - } - if (Optional.IsDefined(PatternType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(PatternType.Value.ToSerialString()); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ResourceTypeAliasPattern IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAliasPattern)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceTypeAliasPattern(document.RootElement, options); - } - - internal static ResourceTypeAliasPattern DeserializeResourceTypeAliasPattern(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string phrase = default; - string variable = default; - ResourceTypeAliasPatternType? type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("phrase"u8)) - { - phrase = property.Value.GetString(); - continue; - } - if (property.NameEquals("variable"u8)) - { - variable = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = property.Value.GetString().ToResourceTypeAliasPatternType(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceTypeAliasPattern(phrase, variable, type, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Phrase), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" phrase: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Phrase)) - { - builder.Append(" phrase: "); - if (Phrase.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Phrase}'''"); - } - else - { - builder.AppendLine($"'{Phrase}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Variable), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" variable: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Variable)) - { - builder.Append(" variable: "); - if (Variable.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Variable}'''"); - } - else - { - builder.AppendLine($"'{Variable}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PatternType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" type: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PatternType)) - { - builder.Append(" type: "); - builder.AppendLine($"'{PatternType.Value.ToSerialString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceTypeAliasPattern)} does not support writing '{options.Format}' format."); - } - } - - ResourceTypeAliasPattern IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceTypeAliasPattern(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceTypeAliasPattern)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPattern.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPattern.cs deleted file mode 100644 index 5c318a2dde..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPattern.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The type of the pattern for an alias path. - public partial class ResourceTypeAliasPattern - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceTypeAliasPattern() - { - } - - /// Initializes a new instance of . - /// The alias pattern phrase. - /// The alias pattern variable. - /// The type of alias pattern. - /// Keeps track of any properties unknown to the library. - internal ResourceTypeAliasPattern(string phrase, string variable, ResourceTypeAliasPatternType? patternType, IDictionary serializedAdditionalRawData) - { - Phrase = phrase; - Variable = variable; - PatternType = patternType; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The alias pattern phrase. - [WirePath("phrase")] - public string Phrase { get; } - /// The alias pattern variable. - [WirePath("variable")] - public string Variable { get; } - /// The type of alias pattern. - [WirePath("type")] - public ResourceTypeAliasPatternType? PatternType { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPatternType.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPatternType.Serialization.cs deleted file mode 100644 index 8faaf01391..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPatternType.Serialization.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.Resources.Models -{ - internal static partial class ResourceTypeAliasPatternTypeExtensions - { - public static string ToSerialString(this ResourceTypeAliasPatternType value) => value switch - { - ResourceTypeAliasPatternType.NotSpecified => "NotSpecified", - ResourceTypeAliasPatternType.Extract => "Extract", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ResourceTypeAliasPatternType value.") - }; - - public static ResourceTypeAliasPatternType ToResourceTypeAliasPatternType(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "NotSpecified")) return ResourceTypeAliasPatternType.NotSpecified; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Extract")) return ResourceTypeAliasPatternType.Extract; - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ResourceTypeAliasPatternType value."); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPatternType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPatternType.cs deleted file mode 100644 index 8ed0430db1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPatternType.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.Resources.Models -{ - /// The type of alias pattern. - public enum ResourceTypeAliasPatternType - { - /// NotSpecified is not allowed. - NotSpecified, - /// Extract is the only allowed value. - Extract - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasType.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasType.Serialization.cs deleted file mode 100644 index 2ddd82d437..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasType.Serialization.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.Resources.Models -{ - internal static partial class ResourceTypeAliasTypeExtensions - { - public static string ToSerialString(this ResourceTypeAliasType value) => value switch - { - ResourceTypeAliasType.NotSpecified => "NotSpecified", - ResourceTypeAliasType.PlainText => "PlainText", - ResourceTypeAliasType.Mask => "Mask", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ResourceTypeAliasType value.") - }; - - public static ResourceTypeAliasType ToResourceTypeAliasType(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "NotSpecified")) return ResourceTypeAliasType.NotSpecified; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "PlainText")) return ResourceTypeAliasType.PlainText; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Mask")) return ResourceTypeAliasType.Mask; - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ResourceTypeAliasType value."); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasType.cs deleted file mode 100644 index b111828d70..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasType.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.Resources.Models -{ - /// The type of the alias. - public enum ResourceTypeAliasType - { - /// Alias type is unknown (same as not providing alias type). - NotSpecified, - /// Alias value is not secret. - PlainText, - /// Alias value is secret. - Mask - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliases.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliases.Serialization.cs deleted file mode 100644 index a7ae258fb4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliases.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceTypeAliases : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAliases)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(ResourceType)) - { - writer.WritePropertyName("resourceType"u8); - writer.WriteStringValue(ResourceType); - } - if (Optional.IsCollectionDefined(Aliases)) - { - writer.WritePropertyName("aliases"u8); - writer.WriteStartArray(); - foreach (var item in Aliases) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ResourceTypeAliases IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAliases)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceTypeAliases(document.RootElement, options); - } - - internal static ResourceTypeAliases DeserializeResourceTypeAliases(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string resourceType = default; - IReadOnlyList aliases = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("resourceType"u8)) - { - resourceType = property.Value.GetString(); - continue; - } - if (property.NameEquals("aliases"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ResourceTypeAlias.DeserializeResourceTypeAlias(item, options)); - } - aliases = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceTypeAliases(resourceType, aliases ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ResourceType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" resourceType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ResourceType)) - { - builder.Append(" resourceType: "); - if (ResourceType.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ResourceType}'''"); - } - else - { - builder.AppendLine($"'{ResourceType}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Aliases), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" aliases: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Aliases)) - { - if (Aliases.Any()) - { - builder.Append(" aliases: "); - builder.AppendLine("["); - foreach (var item in Aliases) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " aliases: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceTypeAliases)} does not support writing '{options.Format}' format."); - } - } - - ResourceTypeAliases IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceTypeAliases(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceTypeAliases)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliases.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliases.cs deleted file mode 100644 index 872c369df5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliases.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The resource type aliases definition. - public partial class ResourceTypeAliases - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceTypeAliases() - { - Aliases = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The resource type name. - /// The aliases for property names. - /// Keeps track of any properties unknown to the library. - internal ResourceTypeAliases(string resourceType, IReadOnlyList aliases, IDictionary serializedAdditionalRawData) - { - ResourceType = resourceType; - Aliases = aliases; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The resource type name. - [WirePath("resourceType")] - public string ResourceType { get; } - /// The aliases for property names. - [WirePath("aliases")] - public IReadOnlyList Aliases { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesMoveContent.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesMoveContent.Serialization.cs deleted file mode 100644 index 53ffc251c8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesMoveContent.Serialization.cs +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourcesMoveContent : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourcesMoveContent)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Resources)) - { - writer.WritePropertyName("resources"u8); - writer.WriteStartArray(); - foreach (var item in Resources) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(TargetResourceGroupId)) - { - writer.WritePropertyName("targetResourceGroup"u8); - writer.WriteStringValue(TargetResourceGroupId); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ResourcesMoveContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourcesMoveContent)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourcesMoveContent(document.RootElement, options); - } - - internal static ResourcesMoveContent DeserializeResourcesMoveContent(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IList resources = default; - ResourceIdentifier targetResourceGroup = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("resources"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - resources = array; - continue; - } - if (property.NameEquals("targetResourceGroup"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - targetResourceGroup = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourcesMoveContent(resources ?? new ChangeTrackingList(), targetResourceGroup, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ResourcesMoveContent)} does not support writing '{options.Format}' format."); - } - } - - ResourcesMoveContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourcesMoveContent(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourcesMoveContent)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesMoveContent.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesMoveContent.cs deleted file mode 100644 index 89139c1b2e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesMoveContent.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Parameters of move resources. - public partial class ResourcesMoveContent - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ResourcesMoveContent() - { - Resources = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The IDs of the resources. - /// The target resource group. - /// Keeps track of any properties unknown to the library. - internal ResourcesMoveContent(IList resources, ResourceIdentifier targetResourceGroupId, IDictionary serializedAdditionalRawData) - { - Resources = resources; - TargetResourceGroupId = targetResourceGroupId; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The IDs of the resources. - [WirePath("resources")] - public IList Resources { get; } - /// The target resource group. - [WirePath("targetResourceGroup")] - public ResourceIdentifier TargetResourceGroupId { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesSku.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesSku.Serialization.cs deleted file mode 100644 index f3919ac07f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesSku.Serialization.cs +++ /dev/null @@ -1,343 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourcesSku : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourcesSku)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(Tier)) - { - writer.WritePropertyName("tier"u8); - writer.WriteStringValue(Tier); - } - if (Optional.IsDefined(Size)) - { - writer.WritePropertyName("size"u8); - writer.WriteStringValue(Size); - } - if (Optional.IsDefined(Family)) - { - writer.WritePropertyName("family"u8); - writer.WriteStringValue(Family); - } - if (Optional.IsDefined(Model)) - { - writer.WritePropertyName("model"u8); - writer.WriteStringValue(Model); - } - if (Optional.IsDefined(Capacity)) - { - writer.WritePropertyName("capacity"u8); - writer.WriteNumberValue(Capacity.Value); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ResourcesSku IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourcesSku)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourcesSku(document.RootElement, options); - } - - internal static ResourcesSku DeserializeResourcesSku(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - string tier = default; - string size = default; - string family = default; - string model = default; - int? capacity = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("tier"u8)) - { - tier = property.Value.GetString(); - continue; - } - if (property.NameEquals("size"u8)) - { - size = property.Value.GetString(); - continue; - } - if (property.NameEquals("family"u8)) - { - family = property.Value.GetString(); - continue; - } - if (property.NameEquals("model"u8)) - { - model = property.Value.GetString(); - continue; - } - if (property.NameEquals("capacity"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - capacity = property.Value.GetInt32(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourcesSku( - name, - tier, - size, - family, - model, - capacity, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Tier), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tier: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Tier)) - { - builder.Append(" tier: "); - if (Tier.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Tier}'''"); - } - else - { - builder.AppendLine($"'{Tier}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Size), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" size: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Size)) - { - builder.Append(" size: "); - if (Size.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Size}'''"); - } - else - { - builder.AppendLine($"'{Size}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Family), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" family: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Family)) - { - builder.Append(" family: "); - if (Family.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Family}'''"); - } - else - { - builder.AppendLine($"'{Family}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Model), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" model: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Model)) - { - builder.Append(" model: "); - if (Model.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Model}'''"); - } - else - { - builder.AppendLine($"'{Model}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Capacity), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" capacity: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Capacity)) - { - builder.Append(" capacity: "); - builder.AppendLine($"{Capacity.Value}"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourcesSku)} does not support writing '{options.Format}' format."); - } - } - - ResourcesSku IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourcesSku(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourcesSku)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesSku.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesSku.cs deleted file mode 100644 index 1aa8907276..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesSku.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// SKU for the resource. - public partial class ResourcesSku - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ResourcesSku() - { - } - - /// Initializes a new instance of . - /// The SKU name. - /// The SKU tier. - /// The SKU size. - /// The SKU family. - /// The SKU model. - /// The SKU capacity. - /// Keeps track of any properties unknown to the library. - internal ResourcesSku(string name, string tier, string size, string family, string model, int? capacity, IDictionary serializedAdditionalRawData) - { - Name = name; - Tier = tier; - Size = size; - Family = family; - Model = model; - Capacity = capacity; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The SKU name. - [WirePath("name")] - public string Name { get; set; } - /// The SKU tier. - [WirePath("tier")] - public string Tier { get; set; } - /// The SKU size. - [WirePath("size")] - public string Size { get; set; } - /// The SKU family. - [WirePath("family")] - public string Family { get; set; } - /// The SKU model. - [WirePath("model")] - public string Model { get; set; } - /// The SKU capacity. - [WirePath("capacity")] - public int? Capacity { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SpendingLimit.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SpendingLimit.Serialization.cs deleted file mode 100644 index 1330415ea3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SpendingLimit.Serialization.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.Resources.Models -{ - internal static partial class SpendingLimitExtensions - { - public static string ToSerialString(this SpendingLimit value) => value switch - { - SpendingLimit.On => "On", - SpendingLimit.Off => "Off", - SpendingLimit.CurrentPeriodOff => "CurrentPeriodOff", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown SpendingLimit value.") - }; - - public static SpendingLimit ToSpendingLimit(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "On")) return SpendingLimit.On; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Off")) return SpendingLimit.Off; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "CurrentPeriodOff")) return SpendingLimit.CurrentPeriodOff; - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown SpendingLimit value."); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SpendingLimit.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SpendingLimit.cs deleted file mode 100644 index f1cf361866..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SpendingLimit.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.Resources.Models -{ - /// The subscription spending limit. - public enum SpendingLimit - { - /// On. - On, - /// Off. - Off, - /// CurrentPeriodOff. - CurrentPeriodOff - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubResource.cs deleted file mode 100644 index b5bc3d1195..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubResource.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Sub-resource. - public partial class SubResource - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// Resource ID. - /// Keeps track of any properties unknown to the library. - internal SubResource(ResourceIdentifier id, IDictionary serializedAdditionalRawData) - { - Id = id; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionListResult.Serialization.cs deleted file mode 100644 index 5b5ebed45e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionListResult.Serialization.cs +++ /dev/null @@ -1,216 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class SubscriptionListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SubscriptionListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - SubscriptionListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SubscriptionListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeSubscriptionListResult(document.RootElement, options); - } - - internal static SubscriptionListResult DeserializeSubscriptionListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(SubscriptionData.DeserializeSubscriptionData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new SubscriptionListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(SubscriptionListResult)} does not support writing '{options.Format}' format."); - } - } - - SubscriptionListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeSubscriptionListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(SubscriptionListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionListResult.cs deleted file mode 100644 index 62586d3820..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionListResult.cs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Subscription list operation response. - internal partial class SubscriptionListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The URL to get the next set of results. - /// is null. - internal SubscriptionListResult(string nextLink) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - Value = new ChangeTrackingList(); - NextLink = nextLink; - } - - /// Initializes a new instance of . - /// An array of subscriptions. - /// The URL to get the next set of results. - /// Keeps track of any properties unknown to the library. - internal SubscriptionListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal SubscriptionListResult() - { - } - - /// An array of subscriptions. - public IReadOnlyList Value { get; } - /// The URL to get the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionPolicies.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionPolicies.Serialization.cs deleted file mode 100644 index 66686ae62b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionPolicies.Serialization.cs +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class SubscriptionPolicies : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SubscriptionPolicies)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(LocationPlacementId)) - { - writer.WritePropertyName("locationPlacementId"u8); - writer.WriteStringValue(LocationPlacementId); - } - if (options.Format != "W" && Optional.IsDefined(QuotaId)) - { - writer.WritePropertyName("quotaId"u8); - writer.WriteStringValue(QuotaId); - } - if (options.Format != "W" && Optional.IsDefined(SpendingLimit)) - { - writer.WritePropertyName("spendingLimit"u8); - writer.WriteStringValue(SpendingLimit.Value.ToSerialString()); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - SubscriptionPolicies IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SubscriptionPolicies)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeSubscriptionPolicies(document.RootElement, options); - } - - internal static SubscriptionPolicies DeserializeSubscriptionPolicies(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string locationPlacementId = default; - string quotaId = default; - SpendingLimit? spendingLimit = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("locationPlacementId"u8)) - { - locationPlacementId = property.Value.GetString(); - continue; - } - if (property.NameEquals("quotaId"u8)) - { - quotaId = property.Value.GetString(); - continue; - } - if (property.NameEquals("spendingLimit"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - spendingLimit = property.Value.GetString().ToSpendingLimit(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new SubscriptionPolicies(locationPlacementId, quotaId, spendingLimit, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(LocationPlacementId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" locationPlacementId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(LocationPlacementId)) - { - builder.Append(" locationPlacementId: "); - if (LocationPlacementId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{LocationPlacementId}'''"); - } - else - { - builder.AppendLine($"'{LocationPlacementId}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(QuotaId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" quotaId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(QuotaId)) - { - builder.Append(" quotaId: "); - if (QuotaId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{QuotaId}'''"); - } - else - { - builder.AppendLine($"'{QuotaId}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SpendingLimit), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" spendingLimit: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SpendingLimit)) - { - builder.Append(" spendingLimit: "); - builder.AppendLine($"'{SpendingLimit.Value.ToSerialString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(SubscriptionPolicies)} does not support writing '{options.Format}' format."); - } - } - - SubscriptionPolicies IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeSubscriptionPolicies(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(SubscriptionPolicies)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionPolicies.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionPolicies.cs deleted file mode 100644 index e953221105..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionPolicies.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Subscription policies. - public partial class SubscriptionPolicies - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal SubscriptionPolicies() - { - } - - /// Initializes a new instance of . - /// The subscription location placement ID. The ID indicates which regions are visible for a subscription. For example, a subscription with a location placement Id of Public_2014-09-01 has access to Azure public regions. - /// The subscription quota ID. - /// The subscription spending limit. - /// Keeps track of any properties unknown to the library. - internal SubscriptionPolicies(string locationPlacementId, string quotaId, SpendingLimit? spendingLimit, IDictionary serializedAdditionalRawData) - { - LocationPlacementId = locationPlacementId; - QuotaId = quotaId; - SpendingLimit = spendingLimit; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The subscription location placement ID. The ID indicates which regions are visible for a subscription. For example, a subscription with a location placement Id of Public_2014-09-01 has access to Azure public regions. - [WirePath("locationPlacementId")] - public string LocationPlacementId { get; } - /// The subscription quota ID. - [WirePath("quotaId")] - public string QuotaId { get; } - /// The subscription spending limit. - [WirePath("spendingLimit")] - public SpendingLimit? SpendingLimit { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionState.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionState.Serialization.cs deleted file mode 100644 index 51a2212e62..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionState.Serialization.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.Resources.Models -{ - internal static partial class SubscriptionStateExtensions - { - public static string ToSerialString(this SubscriptionState value) => value switch - { - SubscriptionState.Enabled => "Enabled", - SubscriptionState.Warned => "Warned", - SubscriptionState.PastDue => "PastDue", - SubscriptionState.Disabled => "Disabled", - SubscriptionState.Deleted => "Deleted", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown SubscriptionState value.") - }; - - public static SubscriptionState ToSubscriptionState(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Enabled")) return SubscriptionState.Enabled; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Warned")) return SubscriptionState.Warned; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "PastDue")) return SubscriptionState.PastDue; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Disabled")) return SubscriptionState.Disabled; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Deleted")) return SubscriptionState.Deleted; - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown SubscriptionState value."); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionState.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionState.cs deleted file mode 100644 index 2c58d11912..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionState.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.Resources.Models -{ - /// The subscription state. Possible values are Enabled, Warned, PastDue, Disabled, and Deleted. - public enum SubscriptionState - { - /// Enabled. - Enabled, - /// Warned. - Warned, - /// PastDue. - PastDue, - /// Disabled. - Disabled, - /// Deleted. - Deleted - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/Tag.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/Tag.Serialization.cs deleted file mode 100644 index fb16f5f47d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/Tag.Serialization.cs +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class Tag : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(Tag)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(TagValues)) - { - writer.WritePropertyName("tags"u8); - writer.WriteStartObject(); - foreach (var item in TagValues) - { - writer.WritePropertyName(item.Key); - writer.WriteStringValue(item.Value); - } - writer.WriteEndObject(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - Tag IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(Tag)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeTag(document.RootElement, options); - } - - internal static Tag DeserializeTag(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IDictionary tags = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("tags"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - tags = dictionary; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new Tag(tags ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TagValues), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tags: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(TagValues)) - { - if (TagValues.Any()) - { - builder.Append(" tags: "); - builder.AppendLine("{"); - foreach (var item in TagValues) - { - builder.Append($" '{item.Key}': "); - if (item.Value == null) - { - builder.Append("null"); - continue; - } - if (item.Value.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{item.Value}'''"); - } - else - { - builder.AppendLine($"'{item.Value}'"); - } - } - builder.AppendLine(" }"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(Tag)} does not support writing '{options.Format}' format."); - } - } - - Tag IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeTag(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(Tag)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/Tag.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/Tag.cs deleted file mode 100644 index 694808ed76..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/Tag.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// A dictionary of name and value pairs. - public partial class Tag - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public Tag() - { - TagValues = new ChangeTrackingDictionary(); - } - - /// Initializes a new instance of . - /// Dictionary of <string>. - /// Keeps track of any properties unknown to the library. - internal Tag(IDictionary tagValues, IDictionary serializedAdditionalRawData) - { - TagValues = tagValues; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TagPatchMode.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TagPatchMode.cs deleted file mode 100644 index a9f204e236..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TagPatchMode.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The operation type for the patch API. - public readonly partial struct TagPatchMode : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public TagPatchMode(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string ReplaceValue = "Replace"; - private const string MergeValue = "Merge"; - private const string DeleteValue = "Delete"; - - /// The 'replace' option replaces the entire set of existing tags with a new set. - public static TagPatchMode Replace { get; } = new TagPatchMode(ReplaceValue); - /// The 'merge' option allows adding tags with new names and updating the values of tags with existing names. - public static TagPatchMode Merge { get; } = new TagPatchMode(MergeValue); - /// The 'delete' option allows selectively deleting tags based on given names or name/value pairs. - public static TagPatchMode Delete { get; } = new TagPatchMode(DeleteValue); - /// Determines if two values are the same. - public static bool operator ==(TagPatchMode left, TagPatchMode right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(TagPatchMode left, TagPatchMode right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator TagPatchMode(string value) => new TagPatchMode(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is TagPatchMode other && Equals(other); - /// - public bool Equals(TagPatchMode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TagResourcePatch.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TagResourcePatch.Serialization.cs deleted file mode 100644 index b9e2ceee21..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TagResourcePatch.Serialization.cs +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class TagResourcePatch : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TagResourcePatch)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(PatchMode)) - { - writer.WritePropertyName("operation"u8); - writer.WriteStringValue(PatchMode.Value.ToString()); - } - if (Optional.IsDefined(Properties)) - { - writer.WritePropertyName("properties"u8); - writer.WriteObjectValue(Properties, options); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - TagResourcePatch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TagResourcePatch)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeTagResourcePatch(document.RootElement, options); - } - - internal static TagResourcePatch DeserializeTagResourcePatch(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - TagPatchMode? operation = default; - Tag properties = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("operation"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - operation = new TagPatchMode(property.Value.GetString()); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - properties = Tag.DeserializeTag(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new TagResourcePatch(operation, properties, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(TagResourcePatch)} does not support writing '{options.Format}' format."); - } - } - - TagResourcePatch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeTagResourcePatch(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(TagResourcePatch)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TagResourcePatch.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TagResourcePatch.cs deleted file mode 100644 index dc4496a3c0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TagResourcePatch.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Wrapper resource for tags patch API request only. - public partial class TagResourcePatch - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public TagResourcePatch() - { - } - - /// Initializes a new instance of . - /// The operation type for the patch API. - /// The set of tags. - /// Keeps track of any properties unknown to the library. - internal TagResourcePatch(TagPatchMode? patchMode, Tag properties, IDictionary serializedAdditionalRawData) - { - PatchMode = patchMode; - Properties = properties; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The operation type for the patch API. - [WirePath("operation")] - public TagPatchMode? PatchMode { get; set; } - /// The set of tags. - internal Tag Properties { get; set; } - /// Dictionary of <string>. - [WirePath("properties.tags")] - public IDictionary TagValues - { - get - { - if (Properties is null) - Properties = new Tag(); - return Properties.TagValues; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantCategory.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantCategory.Serialization.cs deleted file mode 100644 index a3d824a90a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantCategory.Serialization.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.Resources.Models -{ - internal static partial class TenantCategoryExtensions - { - public static string ToSerialString(this TenantCategory value) => value switch - { - TenantCategory.Home => "Home", - TenantCategory.ProjectedBy => "ProjectedBy", - TenantCategory.ManagedBy => "ManagedBy", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown TenantCategory value.") - }; - - public static TenantCategory ToTenantCategory(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Home")) return TenantCategory.Home; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "ProjectedBy")) return TenantCategory.ProjectedBy; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "ManagedBy")) return TenantCategory.ManagedBy; - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown TenantCategory value."); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantCategory.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantCategory.cs deleted file mode 100644 index 4de42a1b2f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantCategory.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.Resources.Models -{ - /// Category of the tenant. - public enum TenantCategory - { - /// Home. - Home, - /// ProjectedBy. - ProjectedBy, - /// ManagedBy. - ManagedBy - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantListResult.Serialization.cs deleted file mode 100644 index a49ae121eb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantListResult.Serialization.cs +++ /dev/null @@ -1,216 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class TenantListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TenantListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - TenantListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TenantListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeTenantListResult(document.RootElement, options); - } - - internal static TenantListResult DeserializeTenantListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(TenantData.DeserializeTenantData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new TenantListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(TenantListResult)} does not support writing '{options.Format}' format."); - } - } - - TenantListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeTenantListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(TenantListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantListResult.cs deleted file mode 100644 index 82c47daaf1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantListResult.cs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Tenant Ids information. - internal partial class TenantListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The URL to use for getting the next set of results. - /// is null. - internal TenantListResult(string nextLink) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - Value = new ChangeTrackingList(); - NextLink = nextLink; - } - - /// Initializes a new instance of . - /// An array of tenants. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal TenantListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal TenantListResult() - { - } - - /// An array of tenants. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProvider.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProvider.Serialization.cs deleted file mode 100644 index 30a4ebe220..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProvider.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class TenantResourceProvider : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TenantResourceProvider)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Namespace)) - { - writer.WritePropertyName("namespace"u8); - writer.WriteStringValue(Namespace); - } - if (options.Format != "W" && Optional.IsCollectionDefined(ResourceTypes)) - { - writer.WritePropertyName("resourceTypes"u8); - writer.WriteStartArray(); - foreach (var item in ResourceTypes) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - TenantResourceProvider IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TenantResourceProvider)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeTenantResourceProvider(document.RootElement, options); - } - - internal static TenantResourceProvider DeserializeTenantResourceProvider(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @namespace = default; - IReadOnlyList resourceTypes = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("namespace"u8)) - { - @namespace = property.Value.GetString(); - continue; - } - if (property.NameEquals("resourceTypes"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ProviderResourceType.DeserializeProviderResourceType(item, options)); - } - resourceTypes = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new TenantResourceProvider(@namespace, resourceTypes ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Namespace), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" namespace: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Namespace)) - { - builder.Append(" namespace: "); - if (Namespace.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Namespace}'''"); - } - else - { - builder.AppendLine($"'{Namespace}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ResourceTypes), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" resourceTypes: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ResourceTypes)) - { - if (ResourceTypes.Any()) - { - builder.Append(" resourceTypes: "); - builder.AppendLine("["); - foreach (var item in ResourceTypes) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " resourceTypes: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(TenantResourceProvider)} does not support writing '{options.Format}' format."); - } - } - - TenantResourceProvider IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeTenantResourceProvider(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(TenantResourceProvider)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProvider.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProvider.cs deleted file mode 100644 index c32fa3cc1a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProvider.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Resource provider information. - public partial class TenantResourceProvider - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal TenantResourceProvider() - { - ResourceTypes = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The namespace of the resource provider. - /// The collection of provider resource types. - /// Keeps track of any properties unknown to the library. - internal TenantResourceProvider(string @namespace, IReadOnlyList resourceTypes, IDictionary serializedAdditionalRawData) - { - Namespace = @namespace; - ResourceTypes = resourceTypes; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The namespace of the resource provider. - [WirePath("namespace")] - public string Namespace { get; } - /// The collection of provider resource types. - [WirePath("resourceTypes")] - public IReadOnlyList ResourceTypes { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProviderListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProviderListResult.Serialization.cs deleted file mode 100644 index 0230f94493..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProviderListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class TenantResourceProviderListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TenantResourceProviderListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - TenantResourceProviderListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TenantResourceProviderListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeTenantResourceProviderListResult(document.RootElement, options); - } - - internal static TenantResourceProviderListResult DeserializeTenantResourceProviderListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(TenantResourceProvider.DeserializeTenantResourceProvider(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new TenantResourceProviderListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(TenantResourceProviderListResult)} does not support writing '{options.Format}' format."); - } - } - - TenantResourceProviderListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeTenantResourceProviderListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(TenantResourceProviderListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProviderListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProviderListResult.cs deleted file mode 100644 index 44043f0767..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProviderListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of resource providers. - internal partial class TenantResourceProviderListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal TenantResourceProviderListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of resource providers. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal TenantResourceProviderListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of resource providers. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TrackedResourceExtendedData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TrackedResourceExtendedData.Serialization.cs deleted file mode 100644 index dfdee13d11..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TrackedResourceExtendedData.Serialization.cs +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class TrackedResourceExtendedData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TrackedResourceExtendedData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - if (Optional.IsDefined(ExtendedLocation)) - { - writer.WritePropertyName("extendedLocation"u8); - JsonSerializer.Serialize(writer, ExtendedLocation, ResourceManagerJsonContext.Default.ExtendedLocation); - } - } - - TrackedResourceExtendedData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TrackedResourceExtendedData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeTrackedResourceExtendedData(document.RootElement, options); - } - - internal static TrackedResourceExtendedData DeserializeTrackedResourceExtendedData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ExtendedLocation extendedLocation = default; - IDictionary tags = default; - AzureLocation location = default; - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("extendedLocation"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - extendedLocation = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.ExtendedLocation); - continue; - } - if (property.NameEquals("tags"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - tags = dictionary; - continue; - } - if (property.NameEquals("location"u8)) - { - location = new AzureLocation(property.Value.GetString()); - continue; - } - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.SystemData); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new TrackedResourceExtendedData( - id, - name, - type, - systemData, - tags ?? new ChangeTrackingDictionary(), - location, - extendedLocation, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Location), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" location: "); - builder.AppendLine(propertyOverride); - } - else - { - builder.Append(" location: "); - builder.AppendLine($"'{Location.ToString()}'"); - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Tags), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tags: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Tags)) - { - if (Tags.Any()) - { - builder.Append(" tags: "); - builder.AppendLine("{"); - foreach (var item in Tags) - { - builder.Append($" '{item.Key}': "); - if (item.Value == null) - { - builder.Append("null"); - continue; - } - if (item.Value.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{item.Value}'''"); - } - else - { - builder.AppendLine($"'{item.Value}'"); - } - } - builder.AppendLine(" }"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ExtendedLocation), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" extendedLocation: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ExtendedLocation)) - { - builder.Append(" extendedLocation: "); - BicepSerializationHelpers.AppendChildObject(builder, ExtendedLocation, options, 2, false, " extendedLocation: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(TrackedResourceExtendedData)} does not support writing '{options.Format}' format."); - } - } - - TrackedResourceExtendedData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeTrackedResourceExtendedData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(TrackedResourceExtendedData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TrackedResourceExtendedData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TrackedResourceExtendedData.cs deleted file mode 100644 index 1474b682eb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/TrackedResourceExtendedData.cs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Specified resource. - public partial class TrackedResourceExtendedData : TrackedResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private protected IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The location. - public TrackedResourceExtendedData(AzureLocation location) : base(location) - { - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The tags. - /// The location. - /// Resource extended location. - /// Keeps track of any properties unknown to the library. - internal TrackedResourceExtendedData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, IDictionary tags, AzureLocation location, ExtendedLocation extendedLocation, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData, tags, location) - { - ExtendedLocation = extendedLocation; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal TrackedResourceExtendedData() - { - } - - /// Resource extended location. - [WirePath("extendedLocation")] - public ExtendedLocation ExtendedLocation { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ZoneMapping.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ZoneMapping.Serialization.cs deleted file mode 100644 index b0d8d11192..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ZoneMapping.Serialization.cs +++ /dev/null @@ -1,228 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ZoneMapping : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ZoneMapping)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Location)) - { - writer.WritePropertyName("location"u8); - writer.WriteStringValue(Location.Value); - } - if (Optional.IsCollectionDefined(Zones)) - { - writer.WritePropertyName("zones"u8); - writer.WriteStartArray(); - foreach (var item in Zones) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ZoneMapping IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ZoneMapping)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeZoneMapping(document.RootElement, options); - } - - internal static ZoneMapping DeserializeZoneMapping(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - AzureLocation? location = default; - IReadOnlyList zones = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("location"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - location = new AzureLocation(property.Value.GetString()); - continue; - } - if (property.NameEquals("zones"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - zones = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ZoneMapping(location, zones ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Location), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" location: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Location)) - { - builder.Append(" location: "); - builder.AppendLine($"'{Location.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Zones), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" zones: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Zones)) - { - if (Zones.Any()) - { - builder.Append(" zones: "); - builder.AppendLine("["); - foreach (var item in Zones) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ZoneMapping)} does not support writing '{options.Format}' format."); - } - } - - ZoneMapping IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeZoneMapping(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ZoneMapping)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ZoneMapping.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ZoneMapping.cs deleted file mode 100644 index 78773bb967..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/Models/ZoneMapping.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The ZoneMapping. - public partial class ZoneMapping - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ZoneMapping() - { - Zones = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The location of the zone mapping. - /// - /// Keeps track of any properties unknown to the library. - internal ZoneMapping(AzureLocation? location, IReadOnlyList zones, IDictionary serializedAdditionalRawData) - { - Location = location; - Zones = zones; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The location of the zone mapping. - [WirePath("location")] - public AzureLocation? Location { get; } - /// Gets the zones. - [WirePath("zones")] - public IReadOnlyList Zones { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentCollection.cs deleted file mode 100644 index c424f0598d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentCollection.cs +++ /dev/null @@ -1,630 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetPolicyAssignments method from an instance of . - /// - public partial class PolicyAssignmentCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _policyAssignmentClientDiagnostics; - private readonly PolicyAssignmentsRestOperations _policyAssignmentRestClient; - - /// Initializes a new instance of the class for mocking. - protected PolicyAssignmentCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal PolicyAssignmentCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _policyAssignmentClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", PolicyAssignmentResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(PolicyAssignmentResource.ResourceType, out string policyAssignmentApiVersion); - _policyAssignmentRestClient = new PolicyAssignmentsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, policyAssignmentApiVersion); - } - - /// - /// This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Create - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy assignment. - /// Parameters for the policy assignment. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string policyAssignmentName, PolicyAssignmentData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _policyAssignmentRestClient.CreateAsync(Id, policyAssignmentName, data, cancellationToken).ConfigureAwait(false); - var uri = _policyAssignmentRestClient.CreateCreateRequestUri(Id, policyAssignmentName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new PolicyAssignmentResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Create - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy assignment. - /// Parameters for the policy assignment. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string policyAssignmentName, PolicyAssignmentData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = _policyAssignmentRestClient.Create(Id, policyAssignmentName, data, cancellationToken); - var uri = _policyAssignmentRestClient.CreateCreateRequestUri(Id, policyAssignmentName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new PolicyAssignmentResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a single policy assignment, given its name and the scope it was created at. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentCollection.Get"); - scope.Start(); - try - { - var response = await _policyAssignmentRestClient.GetAsync(Id, policyAssignmentName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new PolicyAssignmentResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a single policy assignment, given its name and the scope it was created at. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentCollection.Get"); - scope.Start(); - try - { - var response = _policyAssignmentRestClient.Get(Id, policyAssignmentName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new PolicyAssignmentResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the list of all policy assignments associated with the given resource group in the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource group, including those that apply directly or apply from containing scopes, as well as any applied to resources contained within the resource group. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource group, which is everything in the unfiltered list except those applied to resources contained within the resource group. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments - /// - /// - /// Operation Id - /// PolicyAssignments_ListForResourceGroup - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyAssignments - /// - /// - /// Operation Id - /// PolicyAssignments_ListForResource - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyAssignments - /// - /// - /// Operation Id - /// PolicyAssignments_ListForManagementGroup - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyAssignments - /// - /// - /// Operation Id - /// PolicyAssignments_List - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - if (Id.ResourceType == ResourceGroupResource.ResourceType) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _policyAssignmentRestClient.CreateListForResourceGroupRequest(Id.SubscriptionId, Id.ResourceGroupName, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _policyAssignmentRestClient.CreateListForResourceGroupNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new PolicyAssignmentResource(Client, PolicyAssignmentData.DeserializePolicyAssignmentData(e)), _policyAssignmentClientDiagnostics, Pipeline, "PolicyAssignmentCollection.GetAll", "value", "nextLink", cancellationToken); - } - else if (Id.ResourceType == ManagementGroupResource.ResourceType) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _policyAssignmentRestClient.CreateListForManagementGroupRequest(Id.Name, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _policyAssignmentRestClient.CreateListForManagementGroupNextPageRequest(nextLink, Id.Name, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new PolicyAssignmentResource(Client, PolicyAssignmentData.DeserializePolicyAssignmentData(e)), _policyAssignmentClientDiagnostics, Pipeline, "PolicyAssignmentCollection.GetAll", "value", "nextLink", cancellationToken); - } - else if (Id.ResourceType == SubscriptionResource.ResourceType) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _policyAssignmentRestClient.CreateListRequest(Id.SubscriptionId, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _policyAssignmentRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new PolicyAssignmentResource(Client, PolicyAssignmentData.DeserializePolicyAssignmentData(e)), _policyAssignmentClientDiagnostics, Pipeline, "PolicyAssignmentCollection.GetAll", "value", "nextLink", cancellationToken); - } - else - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _policyAssignmentRestClient.CreateListForResourceRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.ResourceType.Namespace, Id.Parent.SubstringAfterProviderNamespace(), Id.ResourceType.GetLastType(), Id.Name, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _policyAssignmentRestClient.CreateListForResourceNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.ResourceType.Namespace, Id.Parent.SubstringAfterProviderNamespace(), Id.ResourceType.GetLastType(), Id.Name, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new PolicyAssignmentResource(Client, PolicyAssignmentData.DeserializePolicyAssignmentData(e)), _policyAssignmentClientDiagnostics, Pipeline, "PolicyAssignmentCollection.GetAll", "value", "nextLink", cancellationToken); - } - } - - /// - /// This operation retrieves the list of all policy assignments associated with the given resource group in the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource group, including those that apply directly or apply from containing scopes, as well as any applied to resources contained within the resource group. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource group, which is everything in the unfiltered list except those applied to resources contained within the resource group. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments - /// - /// - /// Operation Id - /// PolicyAssignments_ListForResourceGroup - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyAssignments - /// - /// - /// Operation Id - /// PolicyAssignments_ListForResource - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyAssignments - /// - /// - /// Operation Id - /// PolicyAssignments_ListForManagementGroup - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyAssignments - /// - /// - /// Operation Id - /// PolicyAssignments_List - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - if (Id.ResourceType == ResourceGroupResource.ResourceType) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _policyAssignmentRestClient.CreateListForResourceGroupRequest(Id.SubscriptionId, Id.ResourceGroupName, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _policyAssignmentRestClient.CreateListForResourceGroupNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new PolicyAssignmentResource(Client, PolicyAssignmentData.DeserializePolicyAssignmentData(e)), _policyAssignmentClientDiagnostics, Pipeline, "PolicyAssignmentCollection.GetAll", "value", "nextLink", cancellationToken); - } - else if (Id.ResourceType == ManagementGroupResource.ResourceType) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _policyAssignmentRestClient.CreateListForManagementGroupRequest(Id.Name, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _policyAssignmentRestClient.CreateListForManagementGroupNextPageRequest(nextLink, Id.Name, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new PolicyAssignmentResource(Client, PolicyAssignmentData.DeserializePolicyAssignmentData(e)), _policyAssignmentClientDiagnostics, Pipeline, "PolicyAssignmentCollection.GetAll", "value", "nextLink", cancellationToken); - } - else if (Id.ResourceType == SubscriptionResource.ResourceType) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _policyAssignmentRestClient.CreateListRequest(Id.SubscriptionId, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _policyAssignmentRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new PolicyAssignmentResource(Client, PolicyAssignmentData.DeserializePolicyAssignmentData(e)), _policyAssignmentClientDiagnostics, Pipeline, "PolicyAssignmentCollection.GetAll", "value", "nextLink", cancellationToken); - } - else - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _policyAssignmentRestClient.CreateListForResourceRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.ResourceType.Namespace, Id.Parent.SubstringAfterProviderNamespace(), Id.ResourceType.GetLastType(), Id.Name, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _policyAssignmentRestClient.CreateListForResourceNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.ResourceType.Namespace, Id.Parent.SubstringAfterProviderNamespace(), Id.ResourceType.GetLastType(), Id.Name, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new PolicyAssignmentResource(Client, PolicyAssignmentData.DeserializePolicyAssignmentData(e)), _policyAssignmentClientDiagnostics, Pipeline, "PolicyAssignmentCollection.GetAll", "value", "nextLink", cancellationToken); - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentCollection.Exists"); - scope.Start(); - try - { - var response = await _policyAssignmentRestClient.GetAsync(Id, policyAssignmentName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentCollection.Exists"); - scope.Start(); - try - { - var response = _policyAssignmentRestClient.Get(Id, policyAssignmentName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _policyAssignmentRestClient.GetAsync(Id, policyAssignmentName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new PolicyAssignmentResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentCollection.GetIfExists"); - scope.Start(); - try - { - var response = _policyAssignmentRestClient.Get(Id, policyAssignmentName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new PolicyAssignmentResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentData.Serialization.cs deleted file mode 100644 index 9b5c12248b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentData.Serialization.cs +++ /dev/null @@ -1,760 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class PolicyAssignmentData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyAssignmentData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - if (Optional.IsDefined(Location)) - { - writer.WritePropertyName("location"u8); - writer.WriteStringValue(Location.Value); - } - if (Optional.IsDefined(ManagedIdentity)) - { - writer.WritePropertyName("identity"u8); - JsonSerializer.Serialize(writer, ManagedIdentity, ResourceManagerJsonContext.Default.ManagedServiceIdentity); - } - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (Optional.IsDefined(PolicyDefinitionId)) - { - writer.WritePropertyName("policyDefinitionId"u8); - writer.WriteStringValue(PolicyDefinitionId); - } - if (options.Format != "W" && Optional.IsDefined(Scope)) - { - writer.WritePropertyName("scope"u8); - writer.WriteStringValue(Scope); - } - if (Optional.IsCollectionDefined(ExcludedScopes)) - { - writer.WritePropertyName("notScopes"u8); - writer.WriteStartArray(); - foreach (var item in ExcludedScopes) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(Parameters)) - { - writer.WritePropertyName("parameters"u8); - writer.WriteStartObject(); - foreach (var item in Parameters) - { - writer.WritePropertyName(item.Key); - writer.WriteObjectValue(item.Value, options); - } - writer.WriteEndObject(); - } - if (Optional.IsDefined(Description)) - { - writer.WritePropertyName("description"u8); - writer.WriteStringValue(Description); - } - if (Optional.IsDefined(Metadata)) - { - writer.WritePropertyName("metadata"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(Metadata); -#else - using (JsonDocument document = JsonDocument.Parse(Metadata, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - if (Optional.IsDefined(EnforcementMode)) - { - writer.WritePropertyName("enforcementMode"u8); - writer.WriteStringValue(EnforcementMode.Value.ToString()); - } - if (Optional.IsCollectionDefined(NonComplianceMessages)) - { - writer.WritePropertyName("nonComplianceMessages"u8); - writer.WriteStartArray(); - foreach (var item in NonComplianceMessages) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(ResourceSelectors)) - { - writer.WritePropertyName("resourceSelectors"u8); - writer.WriteStartArray(); - foreach (var item in ResourceSelectors) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(Overrides)) - { - writer.WritePropertyName("overrides"u8); - writer.WriteStartArray(); - foreach (var item in Overrides) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - writer.WriteEndObject(); - } - - PolicyAssignmentData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyAssignmentData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicyAssignmentData(document.RootElement, options); - } - - internal static PolicyAssignmentData DeserializePolicyAssignmentData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - AzureLocation? location = default; - ManagedServiceIdentity identity = default; - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - string displayName = default; - string policyDefinitionId = default; - string scope = default; - IList notScopes = default; - IDictionary parameters = default; - string description = default; - BinaryData metadata = default; - EnforcementMode? enforcementMode = default; - IList nonComplianceMessages = default; - IList resourceSelectors = default; - IList overrides = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("location"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - location = new AzureLocation(property.Value.GetString()); - continue; - } - if (property.NameEquals("identity"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - identity = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.ManagedServiceIdentity); - continue; - } - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.SystemData); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("displayName"u8)) - { - displayName = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("policyDefinitionId"u8)) - { - policyDefinitionId = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("scope"u8)) - { - scope = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("notScopes"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - notScopes = array; - continue; - } - if (property0.NameEquals("parameters"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property1 in property0.Value.EnumerateObject()) - { - dictionary.Add(property1.Name, ArmPolicyParameterValue.DeserializeArmPolicyParameterValue(property1.Value, options)); - } - parameters = dictionary; - continue; - } - if (property0.NameEquals("description"u8)) - { - description = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("metadata"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - metadata = BinaryData.FromString(property0.Value.GetRawText()); - continue; - } - if (property0.NameEquals("enforcementMode"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - enforcementMode = new EnforcementMode(property0.Value.GetString()); - continue; - } - if (property0.NameEquals("nonComplianceMessages"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(NonComplianceMessage.DeserializeNonComplianceMessage(item, options)); - } - nonComplianceMessages = array; - continue; - } - if (property0.NameEquals("resourceSelectors"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(ResourceSelector.DeserializeResourceSelector(item, options)); - } - resourceSelectors = array; - continue; - } - if (property0.NameEquals("overrides"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(PolicyOverride.DeserializePolicyOverride(item, options)); - } - overrides = array; - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicyAssignmentData( - id, - name, - type, - systemData, - location, - identity, - displayName, - policyDefinitionId, - scope, - notScopes ?? new ChangeTrackingList(), - parameters ?? new ChangeTrackingDictionary(), - description, - metadata, - enforcementMode, - nonComplianceMessages ?? new ChangeTrackingList(), - resourceSelectors ?? new ChangeTrackingList(), - overrides ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Location), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" location: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Location)) - { - builder.Append(" location: "); - builder.AppendLine($"'{Location.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ManagedIdentity), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" identity: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ManagedIdentity)) - { - builder.Append(" identity: "); - BicepSerializationHelpers.AppendChildObject(builder, ManagedIdentity, options, 2, false, " identity: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.Append(" properties:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyDefinitionId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyDefinitionId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PolicyDefinitionId)) - { - builder.Append(" policyDefinitionId: "); - if (PolicyDefinitionId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{PolicyDefinitionId}'''"); - } - else - { - builder.AppendLine($"'{PolicyDefinitionId}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Scope), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" scope: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Scope)) - { - builder.Append(" scope: "); - if (Scope.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Scope}'''"); - } - else - { - builder.AppendLine($"'{Scope}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ExcludedScopes), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" notScopes: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ExcludedScopes)) - { - if (ExcludedScopes.Any()) - { - builder.Append(" notScopes: "); - builder.AppendLine("["); - foreach (var item in ExcludedScopes) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Parameters), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parameters: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Parameters)) - { - if (Parameters.Any()) - { - builder.Append(" parameters: "); - builder.AppendLine("{"); - foreach (var item in Parameters) - { - builder.Append($" '{item.Key}': "); - BicepSerializationHelpers.AppendChildObject(builder, item.Value, options, 6, false, " parameters: "); - } - builder.AppendLine(" }"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Description), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" description: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Description)) - { - builder.Append(" description: "); - if (Description.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Description}'''"); - } - else - { - builder.AppendLine($"'{Description}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Metadata), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" metadata: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Metadata)) - { - builder.Append(" metadata: "); - builder.AppendLine($"'{Metadata.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(EnforcementMode), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" enforcementMode: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(EnforcementMode)) - { - builder.Append(" enforcementMode: "); - builder.AppendLine($"'{EnforcementMode.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NonComplianceMessages), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nonComplianceMessages: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(NonComplianceMessages)) - { - if (NonComplianceMessages.Any()) - { - builder.Append(" nonComplianceMessages: "); - builder.AppendLine("["); - foreach (var item in NonComplianceMessages) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 6, true, " nonComplianceMessages: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ResourceSelectors), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" resourceSelectors: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ResourceSelectors)) - { - if (ResourceSelectors.Any()) - { - builder.Append(" resourceSelectors: "); - builder.AppendLine("["); - foreach (var item in ResourceSelectors) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 6, true, " resourceSelectors: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Overrides), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" overrides: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Overrides)) - { - if (Overrides.Any()) - { - builder.Append(" overrides: "); - builder.AppendLine("["); - foreach (var item in Overrides) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 6, true, " overrides: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine(" }"); - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PolicyAssignmentData)} does not support writing '{options.Format}' format."); - } - } - - PolicyAssignmentData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicyAssignmentData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicyAssignmentData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentData.cs deleted file mode 100644 index f0a246cdc3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentData.cs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the PolicyAssignment data model. - /// The policy assignment. - /// - public partial class PolicyAssignmentData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public PolicyAssignmentData() - { - ExcludedScopes = new ChangeTrackingList(); - Parameters = new ChangeTrackingDictionary(); - NonComplianceMessages = new ChangeTrackingList(); - ResourceSelectors = new ChangeTrackingList(); - Overrides = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The location of the policy assignment. Only required when utilizing managed identity. - /// The managed identity associated with the policy assignment. Current supported identity types: None, SystemAssigned, UserAssigned. - /// The display name of the policy assignment. - /// The ID of the policy definition or policy set definition being assigned. - /// The scope for the policy assignment. - /// The policy's excluded scopes. - /// The parameter values for the assigned policy rule. The keys are the parameter names. - /// This message will be part of response in case of policy violation. - /// The policy assignment metadata. Metadata is an open ended object and is typically a collection of key value pairs. - /// The policy assignment enforcement mode. Possible values are Default and DoNotEnforce. - /// The messages that describe why a resource is non-compliant with the policy. - /// The resource selector list to filter policies by resource properties. - /// The policy property value override. - /// Keeps track of any properties unknown to the library. - internal PolicyAssignmentData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, AzureLocation? location, ManagedServiceIdentity managedIdentity, string displayName, string policyDefinitionId, string scope, IList excludedScopes, IDictionary parameters, string description, BinaryData metadata, EnforcementMode? enforcementMode, IList nonComplianceMessages, IList resourceSelectors, IList overrides, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - Location = location; - ManagedIdentity = managedIdentity; - DisplayName = displayName; - PolicyDefinitionId = policyDefinitionId; - Scope = scope; - ExcludedScopes = excludedScopes; - Parameters = parameters; - Description = description; - Metadata = metadata; - EnforcementMode = enforcementMode; - NonComplianceMessages = nonComplianceMessages; - ResourceSelectors = resourceSelectors; - Overrides = overrides; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The location of the policy assignment. Only required when utilizing managed identity. - [WirePath("location")] - public AzureLocation? Location { get; set; } - /// The managed identity associated with the policy assignment. Current supported identity types: None, SystemAssigned, UserAssigned. - [WirePath("identity")] - public ManagedServiceIdentity ManagedIdentity { get; set; } - /// The display name of the policy assignment. - [WirePath("properties.displayName")] - public string DisplayName { get; set; } - /// The ID of the policy definition or policy set definition being assigned. - [WirePath("properties.policyDefinitionId")] - public string PolicyDefinitionId { get; set; } - /// The scope for the policy assignment. - [WirePath("properties.scope")] - public string Scope { get; } - /// The policy's excluded scopes. - [WirePath("properties.notScopes")] - public IList ExcludedScopes { get; } - /// The parameter values for the assigned policy rule. The keys are the parameter names. - [WirePath("properties.parameters")] - public IDictionary Parameters { get; } - /// This message will be part of response in case of policy violation. - [WirePath("properties.description")] - public string Description { get; set; } - /// - /// The policy assignment metadata. Metadata is an open ended object and is typically a collection of key value pairs. - /// - /// To assign an object to this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("properties.metadata")] - public BinaryData Metadata { get; set; } - /// The policy assignment enforcement mode. Possible values are Default and DoNotEnforce. - [WirePath("properties.enforcementMode")] - public EnforcementMode? EnforcementMode { get; set; } - /// The messages that describe why a resource is non-compliant with the policy. - [WirePath("properties.nonComplianceMessages")] - public IList NonComplianceMessages { get; } - /// The resource selector list to filter policies by resource properties. - [WirePath("properties.resourceSelectors")] - public IList ResourceSelectors { get; } - /// The policy property value override. - [WirePath("properties.overrides")] - public IList Overrides { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentResource.Serialization.cs deleted file mode 100644 index 407fb6014f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class PolicyAssignmentResource : IJsonModel - { - private static PolicyAssignmentData s_dataDeserializationInstance; - private static PolicyAssignmentData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - PolicyAssignmentData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - PolicyAssignmentData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentResource.cs deleted file mode 100644 index be2bed645c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentResource.cs +++ /dev/null @@ -1,342 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a PolicyAssignment along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetPolicyAssignmentResource method. - /// Otherwise you can get one from its parent resource using the GetPolicyAssignment method. - /// - public partial class PolicyAssignmentResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The scope. - /// The policyAssignmentName. - public static ResourceIdentifier CreateResourceIdentifier(string scope, string policyAssignmentName) - { - var resourceId = $"{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _policyAssignmentClientDiagnostics; - private readonly PolicyAssignmentsRestOperations _policyAssignmentRestClient; - private readonly PolicyAssignmentData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Authorization/policyAssignments"; - - /// Initializes a new instance of the class for mocking. - protected PolicyAssignmentResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal PolicyAssignmentResource(ArmClient client, PolicyAssignmentData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal PolicyAssignmentResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _policyAssignmentClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string policyAssignmentApiVersion); - _policyAssignmentRestClient = new PolicyAssignmentsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, policyAssignmentApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual PolicyAssignmentData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// This operation retrieves a single policy assignment, given its name and the scope it was created at. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentResource.Get"); - scope.Start(); - try - { - var response = await _policyAssignmentRestClient.GetAsync(Id.Parent, Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new PolicyAssignmentResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a single policy assignment, given its name and the scope it was created at. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentResource.Get"); - scope.Start(); - try - { - var response = _policyAssignmentRestClient.Get(Id.Parent, Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new PolicyAssignmentResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes a policy assignment, given its name and the scope it was created in. The scope of a policy assignment is the part of its ID preceding '/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Delete - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual async Task> DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentResource.Delete"); - scope.Start(); - try - { - var response = await _policyAssignmentRestClient.DeleteAsync(Id.Parent, Id.Name, cancellationToken).ConfigureAwait(false); - var uri = _policyAssignmentRestClient.CreateDeleteRequestUri(Id.Parent, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new PolicyAssignmentResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes a policy assignment, given its name and the scope it was created in. The scope of a policy assignment is the part of its ID preceding '/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Delete - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentResource.Delete"); - scope.Start(); - try - { - var response = _policyAssignmentRestClient.Delete(Id.Parent, Id.Name, cancellationToken); - var uri = _policyAssignmentRestClient.CreateDeleteRequestUri(Id.Parent, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new PolicyAssignmentResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Update - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Parameters for policy assignment patch request. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(PolicyAssignmentPatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(patch, nameof(patch)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentResource.Update"); - scope.Start(); - try - { - var response = await _policyAssignmentRestClient.UpdateAsync(Id.Parent, Id.Name, patch, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new PolicyAssignmentResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Update - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Parameters for policy assignment patch request. - /// The cancellation token to use. - /// is null. - public virtual Response Update(PolicyAssignmentPatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(patch, nameof(patch)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentResource.Update"); - scope.Start(); - try - { - var response = _policyAssignmentRestClient.Update(Id.Parent, Id.Name, patch, cancellationToken); - return Response.FromValue(new PolicyAssignmentResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyDefinitionData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyDefinitionData.Serialization.cs deleted file mode 100644 index 9297c29849..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyDefinitionData.Serialization.cs +++ /dev/null @@ -1,492 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class PolicyDefinitionData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyDefinitionData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (Optional.IsDefined(PolicyType)) - { - writer.WritePropertyName("policyType"u8); - writer.WriteStringValue(PolicyType.Value.ToString()); - } - if (Optional.IsDefined(Mode)) - { - writer.WritePropertyName("mode"u8); - writer.WriteStringValue(Mode); - } - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (Optional.IsDefined(Description)) - { - writer.WritePropertyName("description"u8); - writer.WriteStringValue(Description); - } - if (Optional.IsDefined(PolicyRule)) - { - writer.WritePropertyName("policyRule"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(PolicyRule); -#else - using (JsonDocument document = JsonDocument.Parse(PolicyRule, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - if (Optional.IsDefined(Metadata)) - { - writer.WritePropertyName("metadata"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(Metadata); -#else - using (JsonDocument document = JsonDocument.Parse(Metadata, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - if (Optional.IsCollectionDefined(Parameters)) - { - writer.WritePropertyName("parameters"u8); - writer.WriteStartObject(); - foreach (var item in Parameters) - { - writer.WritePropertyName(item.Key); - writer.WriteObjectValue(item.Value, options); - } - writer.WriteEndObject(); - } - writer.WriteEndObject(); - } - - PolicyDefinitionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyDefinitionData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicyDefinitionData(document.RootElement, options); - } - - internal static PolicyDefinitionData DeserializePolicyDefinitionData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - PolicyType? policyType = default; - string mode = default; - string displayName = default; - string description = default; - BinaryData policyRule = default; - BinaryData metadata = default; - IDictionary parameters = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.SystemData); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("policyType"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - policyType = new PolicyType(property0.Value.GetString()); - continue; - } - if (property0.NameEquals("mode"u8)) - { - mode = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("displayName"u8)) - { - displayName = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("description"u8)) - { - description = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("policyRule"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - policyRule = BinaryData.FromString(property0.Value.GetRawText()); - continue; - } - if (property0.NameEquals("metadata"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - metadata = BinaryData.FromString(property0.Value.GetRawText()); - continue; - } - if (property0.NameEquals("parameters"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property1 in property0.Value.EnumerateObject()) - { - dictionary.Add(property1.Name, ArmPolicyParameter.DeserializeArmPolicyParameter(property1.Value, options)); - } - parameters = dictionary; - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicyDefinitionData( - id, - name, - type, - systemData, - policyType, - mode, - displayName, - description, - policyRule, - metadata, - parameters ?? new ChangeTrackingDictionary(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.Append(" properties:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PolicyType)) - { - builder.Append(" policyType: "); - builder.AppendLine($"'{PolicyType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Mode), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" mode: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Mode)) - { - builder.Append(" mode: "); - if (Mode.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Mode}'''"); - } - else - { - builder.AppendLine($"'{Mode}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Description), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" description: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Description)) - { - builder.Append(" description: "); - if (Description.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Description}'''"); - } - else - { - builder.AppendLine($"'{Description}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyRule), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyRule: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PolicyRule)) - { - builder.Append(" policyRule: "); - builder.AppendLine($"'{PolicyRule.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Metadata), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" metadata: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Metadata)) - { - builder.Append(" metadata: "); - builder.AppendLine($"'{Metadata.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Parameters), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parameters: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Parameters)) - { - if (Parameters.Any()) - { - builder.Append(" parameters: "); - builder.AppendLine("{"); - foreach (var item in Parameters) - { - builder.Append($" '{item.Key}': "); - BicepSerializationHelpers.AppendChildObject(builder, item.Value, options, 6, false, " parameters: "); - } - builder.AppendLine(" }"); - } - } - } - - builder.AppendLine(" }"); - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PolicyDefinitionData)} does not support writing '{options.Format}' format."); - } - } - - PolicyDefinitionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicyDefinitionData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicyDefinitionData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyDefinitionData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyDefinitionData.cs deleted file mode 100644 index 6689f9af87..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicyDefinitionData.cs +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the PolicyDefinition data model. - /// The policy definition. - /// - public partial class PolicyDefinitionData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public PolicyDefinitionData() - { - Parameters = new ChangeTrackingDictionary(); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static. - /// The policy definition mode. Some examples are All, Indexed, Microsoft.KeyVault.Data. - /// The display name of the policy definition. - /// The policy definition description. - /// The policy rule. - /// The policy definition metadata. Metadata is an open ended object and is typically a collection of key value pairs. - /// The parameter definitions for parameters used in the policy rule. The keys are the parameter names. - /// Keeps track of any properties unknown to the library. - internal PolicyDefinitionData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, PolicyType? policyType, string mode, string displayName, string description, BinaryData policyRule, BinaryData metadata, IDictionary parameters, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - PolicyType = policyType; - Mode = mode; - DisplayName = displayName; - Description = description; - PolicyRule = policyRule; - Metadata = metadata; - Parameters = parameters; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static. - [WirePath("properties.policyType")] - public PolicyType? PolicyType { get; set; } - /// The policy definition mode. Some examples are All, Indexed, Microsoft.KeyVault.Data. - [WirePath("properties.mode")] - public string Mode { get; set; } - /// The display name of the policy definition. - [WirePath("properties.displayName")] - public string DisplayName { get; set; } - /// The policy definition description. - [WirePath("properties.description")] - public string Description { get; set; } - /// - /// The policy rule. - /// - /// To assign an object to this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("properties.policyRule")] - public BinaryData PolicyRule { get; set; } - /// - /// The policy definition metadata. Metadata is an open ended object and is typically a collection of key value pairs. - /// - /// To assign an object to this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("properties.metadata")] - public BinaryData Metadata { get; set; } - /// The parameter definitions for parameters used in the policy rule. The keys are the parameter names. - [WirePath("properties.parameters")] - public IDictionary Parameters { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicySetDefinitionData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicySetDefinitionData.Serialization.cs deleted file mode 100644 index 54e1be4d49..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicySetDefinitionData.Serialization.cs +++ /dev/null @@ -1,517 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class PolicySetDefinitionData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicySetDefinitionData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (Optional.IsDefined(PolicyType)) - { - writer.WritePropertyName("policyType"u8); - writer.WriteStringValue(PolicyType.Value.ToString()); - } - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (Optional.IsDefined(Description)) - { - writer.WritePropertyName("description"u8); - writer.WriteStringValue(Description); - } - if (Optional.IsDefined(Metadata)) - { - writer.WritePropertyName("metadata"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(Metadata); -#else - using (JsonDocument document = JsonDocument.Parse(Metadata, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - if (Optional.IsCollectionDefined(Parameters)) - { - writer.WritePropertyName("parameters"u8); - writer.WriteStartObject(); - foreach (var item in Parameters) - { - writer.WritePropertyName(item.Key); - writer.WriteObjectValue(item.Value, options); - } - writer.WriteEndObject(); - } - if (Optional.IsCollectionDefined(PolicyDefinitions)) - { - writer.WritePropertyName("policyDefinitions"u8); - writer.WriteStartArray(); - foreach (var item in PolicyDefinitions) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(PolicyDefinitionGroups)) - { - writer.WritePropertyName("policyDefinitionGroups"u8); - writer.WriteStartArray(); - foreach (var item in PolicyDefinitionGroups) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - writer.WriteEndObject(); - } - - PolicySetDefinitionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicySetDefinitionData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicySetDefinitionData(document.RootElement, options); - } - - internal static PolicySetDefinitionData DeserializePolicySetDefinitionData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - PolicyType? policyType = default; - string displayName = default; - string description = default; - BinaryData metadata = default; - IDictionary parameters = default; - IList policyDefinitions = default; - IList policyDefinitionGroups = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.SystemData); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("policyType"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - policyType = new PolicyType(property0.Value.GetString()); - continue; - } - if (property0.NameEquals("displayName"u8)) - { - displayName = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("description"u8)) - { - description = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("metadata"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - metadata = BinaryData.FromString(property0.Value.GetRawText()); - continue; - } - if (property0.NameEquals("parameters"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property1 in property0.Value.EnumerateObject()) - { - dictionary.Add(property1.Name, ArmPolicyParameter.DeserializeArmPolicyParameter(property1.Value, options)); - } - parameters = dictionary; - continue; - } - if (property0.NameEquals("policyDefinitions"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(PolicyDefinitionReference.DeserializePolicyDefinitionReference(item, options)); - } - policyDefinitions = array; - continue; - } - if (property0.NameEquals("policyDefinitionGroups"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(PolicyDefinitionGroup.DeserializePolicyDefinitionGroup(item, options)); - } - policyDefinitionGroups = array; - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicySetDefinitionData( - id, - name, - type, - systemData, - policyType, - displayName, - description, - metadata, - parameters ?? new ChangeTrackingDictionary(), - policyDefinitions ?? new ChangeTrackingList(), - policyDefinitionGroups ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.Append(" properties:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PolicyType)) - { - builder.Append(" policyType: "); - builder.AppendLine($"'{PolicyType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Description), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" description: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Description)) - { - builder.Append(" description: "); - if (Description.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Description}'''"); - } - else - { - builder.AppendLine($"'{Description}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Metadata), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" metadata: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Metadata)) - { - builder.Append(" metadata: "); - builder.AppendLine($"'{Metadata.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Parameters), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parameters: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Parameters)) - { - if (Parameters.Any()) - { - builder.Append(" parameters: "); - builder.AppendLine("{"); - foreach (var item in Parameters) - { - builder.Append($" '{item.Key}': "); - BicepSerializationHelpers.AppendChildObject(builder, item.Value, options, 6, false, " parameters: "); - } - builder.AppendLine(" }"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyDefinitions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyDefinitions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(PolicyDefinitions)) - { - if (PolicyDefinitions.Any()) - { - builder.Append(" policyDefinitions: "); - builder.AppendLine("["); - foreach (var item in PolicyDefinitions) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 6, true, " policyDefinitions: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyDefinitionGroups), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyDefinitionGroups: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(PolicyDefinitionGroups)) - { - if (PolicyDefinitionGroups.Any()) - { - builder.Append(" policyDefinitionGroups: "); - builder.AppendLine("["); - foreach (var item in PolicyDefinitionGroups) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 6, true, " policyDefinitionGroups: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine(" }"); - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PolicySetDefinitionData)} does not support writing '{options.Format}' format."); - } - } - - PolicySetDefinitionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicySetDefinitionData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicySetDefinitionData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicySetDefinitionData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicySetDefinitionData.cs deleted file mode 100644 index 22dae46c74..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/PolicySetDefinitionData.cs +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the PolicySetDefinition data model. - /// The policy set definition. - /// - public partial class PolicySetDefinitionData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public PolicySetDefinitionData() - { - Parameters = new ChangeTrackingDictionary(); - PolicyDefinitions = new ChangeTrackingList(); - PolicyDefinitionGroups = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static. - /// The display name of the policy set definition. - /// The policy set definition description. - /// The policy set definition metadata. Metadata is an open ended object and is typically a collection of key value pairs. - /// The policy set definition parameters that can be used in policy definition references. - /// An array of policy definition references. - /// The metadata describing groups of policy definition references within the policy set definition. - /// Keeps track of any properties unknown to the library. - internal PolicySetDefinitionData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, PolicyType? policyType, string displayName, string description, BinaryData metadata, IDictionary parameters, IList policyDefinitions, IList policyDefinitionGroups, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - PolicyType = policyType; - DisplayName = displayName; - Description = description; - Metadata = metadata; - Parameters = parameters; - PolicyDefinitions = policyDefinitions; - PolicyDefinitionGroups = policyDefinitionGroups; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static. - [WirePath("properties.policyType")] - public PolicyType? PolicyType { get; set; } - /// The display name of the policy set definition. - [WirePath("properties.displayName")] - public string DisplayName { get; set; } - /// The policy set definition description. - [WirePath("properties.description")] - public string Description { get; set; } - /// - /// The policy set definition metadata. Metadata is an open ended object and is typically a collection of key value pairs. - /// - /// To assign an object to this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("properties.metadata")] - public BinaryData Metadata { get; set; } - /// The policy set definition parameters that can be used in policy definition references. - [WirePath("properties.parameters")] - public IDictionary Parameters { get; } - /// An array of policy definition references. - [WirePath("properties.policyDefinitions")] - public IList PolicyDefinitions { get; } - /// The metadata describing groups of policy definition references within the policy set definition. - [WirePath("properties.policyDefinitionGroups")] - public IList PolicyDefinitionGroups { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupCollection.cs deleted file mode 100644 index 6fa5910de7..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupCollection.cs +++ /dev/null @@ -1,500 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetResourceGroups method from an instance of . - /// - public partial class ResourceGroupCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _resourceGroupClientDiagnostics; - private readonly ResourceGroupsRestOperations _resourceGroupRestClient; - - /// Initializes a new instance of the class for mocking. - protected ResourceGroupCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal ResourceGroupCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _resourceGroupClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceGroupResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceGroupResource.ResourceType, out string resourceGroupApiVersion); - _resourceGroupRestClient = new ResourceGroupsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, resourceGroupApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != SubscriptionResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, SubscriptionResource.ResourceType), nameof(id)); - } - - /// - /// Creates or updates a resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the resource group to create or update. Can include alphanumeric, underscore, parentheses, hyphen, period (except at end), and Unicode characters that match the allowed characters. - /// Parameters supplied to the create or update a resource group. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string resourceGroupName, ResourceGroupData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _resourceGroupRestClient.CreateOrUpdateAsync(Id.SubscriptionId, resourceGroupName, data, cancellationToken).ConfigureAwait(false); - var uri = _resourceGroupRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, resourceGroupName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ResourceGroupResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Creates or updates a resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the resource group to create or update. Can include alphanumeric, underscore, parentheses, hyphen, period (except at end), and Unicode characters that match the allowed characters. - /// Parameters supplied to the create or update a resource group. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string resourceGroupName, ResourceGroupData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = _resourceGroupRestClient.CreateOrUpdate(Id.SubscriptionId, resourceGroupName, data, cancellationToken); - var uri = _resourceGroupRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, resourceGroupName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ResourceGroupResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets a resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string resourceGroupName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupCollection.Get"); - scope.Start(); - try - { - var response = await _resourceGroupRestClient.GetAsync(Id.SubscriptionId, resourceGroupName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ResourceGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets a resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string resourceGroupName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupCollection.Get"); - scope.Start(); - try - { - var response = _resourceGroupRestClient.Get(Id.SubscriptionId, resourceGroupName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ResourceGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets all the resource groups for a subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups - /// - /// - /// Operation Id - /// ResourceGroups_List - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. - /// The number of results to return. If null is passed, returns all resource groups. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _resourceGroupRestClient.CreateListRequest(Id.SubscriptionId, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _resourceGroupRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new ResourceGroupResource(Client, ResourceGroupData.DeserializeResourceGroupData(e)), _resourceGroupClientDiagnostics, Pipeline, "ResourceGroupCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Gets all the resource groups for a subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups - /// - /// - /// Operation Id - /// ResourceGroups_List - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. - /// The number of results to return. If null is passed, returns all resource groups. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _resourceGroupRestClient.CreateListRequest(Id.SubscriptionId, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _resourceGroupRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new ResourceGroupResource(Client, ResourceGroupData.DeserializeResourceGroupData(e)), _resourceGroupClientDiagnostics, Pipeline, "ResourceGroupCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string resourceGroupName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupCollection.Exists"); - scope.Start(); - try - { - var response = await _resourceGroupRestClient.GetAsync(Id.SubscriptionId, resourceGroupName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string resourceGroupName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupCollection.Exists"); - scope.Start(); - try - { - var response = _resourceGroupRestClient.Get(Id.SubscriptionId, resourceGroupName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string resourceGroupName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _resourceGroupRestClient.GetAsync(Id.SubscriptionId, resourceGroupName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ResourceGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string resourceGroupName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupCollection.GetIfExists"); - scope.Start(); - try - { - var response = _resourceGroupRestClient.Get(Id.SubscriptionId, resourceGroupName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ResourceGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupData.Serialization.cs deleted file mode 100644 index 0e82804dca..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupData.Serialization.cs +++ /dev/null @@ -1,352 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class ResourceGroupData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - if (Optional.IsDefined(Properties)) - { - writer.WritePropertyName("properties"u8); - writer.WriteObjectValue(Properties, options); - } - if (Optional.IsDefined(ManagedBy)) - { - writer.WritePropertyName("managedBy"u8); - writer.WriteStringValue(ManagedBy); - } - } - - ResourceGroupData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceGroupData(document.RootElement, options); - } - - internal static ResourceGroupData DeserializeResourceGroupData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceGroupProperties properties = default; - string managedBy = default; - IDictionary tags = default; - AzureLocation location = default; - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - properties = ResourceGroupProperties.DeserializeResourceGroupProperties(property.Value, options); - continue; - } - if (property.NameEquals("managedBy"u8)) - { - managedBy = property.Value.GetString(); - continue; - } - if (property.NameEquals("tags"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - tags = dictionary; - continue; - } - if (property.NameEquals("location"u8)) - { - location = new AzureLocation(property.Value.GetString()); - continue; - } - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.SystemData); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceGroupData( - id, - name, - type, - systemData, - tags ?? new ChangeTrackingDictionary(), - location, - properties, - managedBy, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Location), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" location: "); - builder.AppendLine(propertyOverride); - } - else - { - builder.Append(" location: "); - builder.AppendLine($"'{Location.ToString()}'"); - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Tags), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tags: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Tags)) - { - if (Tags.Any()) - { - builder.Append(" tags: "); - builder.AppendLine("{"); - foreach (var item in Tags) - { - builder.Append($" '{item.Key}': "); - if (item.Value == null) - { - builder.Append("null"); - continue; - } - if (item.Value.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{item.Value}'''"); - } - else - { - builder.AppendLine($"'{item.Value}'"); - } - } - builder.AppendLine(" }"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue("ResourceGroupProvisioningState", out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" properties: "); - builder.AppendLine("{"); - builder.Append(" provisioningState: "); - builder.AppendLine(propertyOverride); - builder.AppendLine(" }"); - } - else - { - if (Optional.IsDefined(Properties)) - { - builder.Append(" properties: "); - BicepSerializationHelpers.AppendChildObject(builder, Properties, options, 2, false, " properties: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ManagedBy), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" managedBy: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ManagedBy)) - { - builder.Append(" managedBy: "); - if (ManagedBy.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ManagedBy}'''"); - } - else - { - builder.AppendLine($"'{ManagedBy}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceGroupData)} does not support writing '{options.Format}' format."); - } - } - - ResourceGroupData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceGroupData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceGroupData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupData.cs deleted file mode 100644 index 86a684655c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupData.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the ResourceGroup data model. - /// Resource group information. - /// - public partial class ResourceGroupData : TrackedResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The location. - public ResourceGroupData(AzureLocation location) : base(location) - { - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The tags. - /// The location. - /// The resource group properties. - /// The ID of the resource that manages this resource group. - /// Keeps track of any properties unknown to the library. - internal ResourceGroupData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, IDictionary tags, AzureLocation location, ResourceGroupProperties properties, string managedBy, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData, tags, location) - { - Properties = properties; - ManagedBy = managedBy; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal ResourceGroupData() - { - } - - /// The resource group properties. - internal ResourceGroupProperties Properties { get; set; } - /// The provisioning state. - [WirePath("properties.provisioningState")] - public string ResourceGroupProvisioningState - { - get => Properties is null ? default : Properties.ProvisioningState; - } - - /// The ID of the resource that manages this resource group. - [WirePath("managedBy")] - public string ManagedBy { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupResource.Serialization.cs deleted file mode 100644 index 65a084b9bc..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class ResourceGroupResource : IJsonModel - { - private static ResourceGroupData s_dataDeserializationInstance; - private static ResourceGroupData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - ResourceGroupData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - ResourceGroupData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupResource.cs deleted file mode 100644 index 049966950d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceGroupResource.cs +++ /dev/null @@ -1,980 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a ResourceGroup along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetResourceGroupResource method. - /// Otherwise you can get one from its parent resource using the GetResourceGroup method. - /// - public partial class ResourceGroupResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The subscriptionId. - /// The resourceGroupName. - public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName) - { - var resourceId = $"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _resourceGroupClientDiagnostics; - private readonly ResourceGroupsRestOperations _resourceGroupRestClient; - private readonly ClientDiagnostics _resourceGroupResourcesClientDiagnostics; - private readonly ResourcesRestOperations _resourceGroupResourcesRestClient; - private readonly ResourceGroupData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Resources/resourceGroups"; - - /// Initializes a new instance of the class for mocking. - protected ResourceGroupResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal ResourceGroupResource(ArmClient client, ResourceGroupData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal ResourceGroupResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _resourceGroupClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string resourceGroupApiVersion); - _resourceGroupRestClient = new ResourceGroupsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, resourceGroupApiVersion); - _resourceGroupResourcesClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string resourceGroupResourcesApiVersion); - _resourceGroupResourcesRestClient = new ResourcesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, resourceGroupResourcesApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual ResourceGroupData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// Gets a resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.Get"); - scope.Start(); - try - { - var response = await _resourceGroupRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ResourceGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets a resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.Get"); - scope.Start(); - try - { - var response = _resourceGroupRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ResourceGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// When you delete a resource group, all of its resources are also deleted. Deleting a resource group deletes all of its template deployments and currently stored operations. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Delete - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The resource types you want to force delete. Currently, only the following is supported: forceDeletionTypes=Microsoft.Compute/virtualMachines,Microsoft.Compute/virtualMachineScaleSets. - /// The cancellation token to use. - public virtual async Task DeleteAsync(WaitUntil waitUntil, string forceDeletionTypes = null, CancellationToken cancellationToken = default) - { - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.Delete"); - scope.Start(); - try - { - var response = await _resourceGroupRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, forceDeletionTypes, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(_resourceGroupClientDiagnostics, Pipeline, _resourceGroupRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, forceDeletionTypes).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// When you delete a resource group, all of its resources are also deleted. Deleting a resource group deletes all of its template deployments and currently stored operations. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Delete - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The resource types you want to force delete. Currently, only the following is supported: forceDeletionTypes=Microsoft.Compute/virtualMachines,Microsoft.Compute/virtualMachineScaleSets. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, string forceDeletionTypes = null, CancellationToken cancellationToken = default) - { - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.Delete"); - scope.Start(); - try - { - var response = _resourceGroupRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, forceDeletionTypes, cancellationToken); - var operation = new ResourcesArmOperation(_resourceGroupClientDiagnostics, Pipeline, _resourceGroupRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, forceDeletionTypes).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Resource groups can be updated through a simple PATCH operation to a group address. The format of the request is the same as that for creating a resource group. If a field is unspecified, the current value is retained. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Update - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Parameters supplied to update a resource group. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(ResourceGroupPatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(patch, nameof(patch)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.Update"); - scope.Start(); - try - { - var response = await _resourceGroupRestClient.UpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, patch, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new ResourceGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Resource groups can be updated through a simple PATCH operation to a group address. The format of the request is the same as that for creating a resource group. If a field is unspecified, the current value is retained. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Update - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Parameters supplied to update a resource group. - /// The cancellation token to use. - /// is null. - public virtual Response Update(ResourceGroupPatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(patch, nameof(patch)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.Update"); - scope.Start(); - try - { - var response = _resourceGroupRestClient.Update(Id.SubscriptionId, Id.ResourceGroupName, patch, cancellationToken); - return Response.FromValue(new ResourceGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// The resources to be moved must be in the same source resource group in the source subscription being used. The target resource group may be in a different subscription. When moving resources, both the source group and the target group are locked for the duration of the operation. Write and delete operations are blocked on the groups until the move completes. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourceGroups/{sourceResourceGroupName}/moveResources - /// - /// - /// Operation Id - /// Resources_MoveResources - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Parameters for moving resources. - /// The cancellation token to use. - /// is null. - public virtual async Task MoveResourcesAsync(WaitUntil waitUntil, ResourcesMoveContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = _resourceGroupResourcesClientDiagnostics.CreateScope("ResourceGroupResource.MoveResources"); - scope.Start(); - try - { - var response = await _resourceGroupResourcesRestClient.MoveResourcesAsync(Id.SubscriptionId, Id.ResourceGroupName, content, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(_resourceGroupResourcesClientDiagnostics, Pipeline, _resourceGroupResourcesRestClient.CreateMoveResourcesRequest(Id.SubscriptionId, Id.ResourceGroupName, content).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// The resources to be moved must be in the same source resource group in the source subscription being used. The target resource group may be in a different subscription. When moving resources, both the source group and the target group are locked for the duration of the operation. Write and delete operations are blocked on the groups until the move completes. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourceGroups/{sourceResourceGroupName}/moveResources - /// - /// - /// Operation Id - /// Resources_MoveResources - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Parameters for moving resources. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation MoveResources(WaitUntil waitUntil, ResourcesMoveContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = _resourceGroupResourcesClientDiagnostics.CreateScope("ResourceGroupResource.MoveResources"); - scope.Start(); - try - { - var response = _resourceGroupResourcesRestClient.MoveResources(Id.SubscriptionId, Id.ResourceGroupName, content, cancellationToken); - var operation = new ResourcesArmOperation(_resourceGroupResourcesClientDiagnostics, Pipeline, _resourceGroupResourcesRestClient.CreateMoveResourcesRequest(Id.SubscriptionId, Id.ResourceGroupName, content).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation checks whether the specified resources can be moved to the target. The resources to be moved must be in the same source resource group in the source subscription being used. The target resource group may be in a different subscription. If validation succeeds, it returns HTTP response code 204 (no content). If validation fails, it returns HTTP response code 409 (Conflict) with an error message. Retrieve the URL in the Location header value to check the result of the long-running operation. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourceGroups/{sourceResourceGroupName}/validateMoveResources - /// - /// - /// Operation Id - /// Resources_ValidateMoveResources - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Parameters for moving resources. - /// The cancellation token to use. - /// is null. - public virtual async Task ValidateMoveResourcesAsync(WaitUntil waitUntil, ResourcesMoveContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = _resourceGroupResourcesClientDiagnostics.CreateScope("ResourceGroupResource.ValidateMoveResources"); - scope.Start(); - try - { - var response = await _resourceGroupResourcesRestClient.ValidateMoveResourcesAsync(Id.SubscriptionId, Id.ResourceGroupName, content, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(_resourceGroupResourcesClientDiagnostics, Pipeline, _resourceGroupResourcesRestClient.CreateValidateMoveResourcesRequest(Id.SubscriptionId, Id.ResourceGroupName, content).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation checks whether the specified resources can be moved to the target. The resources to be moved must be in the same source resource group in the source subscription being used. The target resource group may be in a different subscription. If validation succeeds, it returns HTTP response code 204 (no content). If validation fails, it returns HTTP response code 409 (Conflict) with an error message. Retrieve the URL in the Location header value to check the result of the long-running operation. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourceGroups/{sourceResourceGroupName}/validateMoveResources - /// - /// - /// Operation Id - /// Resources_ValidateMoveResources - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Parameters for moving resources. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation ValidateMoveResources(WaitUntil waitUntil, ResourcesMoveContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = _resourceGroupResourcesClientDiagnostics.CreateScope("ResourceGroupResource.ValidateMoveResources"); - scope.Start(); - try - { - var response = _resourceGroupResourcesRestClient.ValidateMoveResources(Id.SubscriptionId, Id.ResourceGroupName, content, cancellationToken); - var operation = new ResourcesArmOperation(_resourceGroupResourcesClientDiagnostics, Pipeline, _resourceGroupResourcesRestClient.CreateValidateMoveResourcesRequest(Id.SubscriptionId, Id.ResourceGroupName, content).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Captures the specified resource group as a template. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/exportTemplate - /// - /// - /// Operation Id - /// ResourceGroups_ExportTemplate - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Parameters for exporting the template. - /// The cancellation token to use. - /// is null. - public virtual async Task> ExportTemplateAsync(WaitUntil waitUntil, ExportTemplate exportTemplate, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(exportTemplate, nameof(exportTemplate)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.ExportTemplate"); - scope.Start(); - try - { - var response = await _resourceGroupRestClient.ExportTemplateAsync(Id.SubscriptionId, Id.ResourceGroupName, exportTemplate, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(new ResourceGroupExportResultOperationSource(), _resourceGroupClientDiagnostics, Pipeline, _resourceGroupRestClient.CreateExportTemplateRequest(Id.SubscriptionId, Id.ResourceGroupName, exportTemplate).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Captures the specified resource group as a template. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/exportTemplate - /// - /// - /// Operation Id - /// ResourceGroups_ExportTemplate - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Parameters for exporting the template. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation ExportTemplate(WaitUntil waitUntil, ExportTemplate exportTemplate, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(exportTemplate, nameof(exportTemplate)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.ExportTemplate"); - scope.Start(); - try - { - var response = _resourceGroupRestClient.ExportTemplate(Id.SubscriptionId, Id.ResourceGroupName, exportTemplate, cancellationToken); - var operation = new ResourcesArmOperation(new ResourceGroupExportResultOperationSource(), _resourceGroupClientDiagnostics, Pipeline, _resourceGroupRestClient.CreateExportTemplateRequest(Id.SubscriptionId, Id.ResourceGroupName, exportTemplate).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Add a tag to the current resource. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The key for the tag. - /// The value for the tag. - /// The cancellation token to use. - /// or is null. - public virtual async Task> AddTagAsync(string key, string value, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(key, nameof(key)); - Argument.AssertNotNull(value, nameof(value)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.AddTag"); - scope.Start(); - try - { - if (await CanUseTagResourceAsync(cancellationToken: cancellationToken).ConfigureAwait(false)) - { - var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false); - originalTags.Value.Data.TagValues[key] = value; - await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false); - var originalResponse = await _resourceGroupRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new ResourceGroupResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - else - { - var current = (await GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false)).Value.Data; - var patch = new ResourceGroupPatch(); - foreach (var tag in current.Tags) - { - patch.Tags.Add(tag); - } - patch.Tags[key] = value; - var result = await UpdateAsync(patch, cancellationToken: cancellationToken).ConfigureAwait(false); - return result; - } - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Add a tag to the current resource. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The key for the tag. - /// The value for the tag. - /// The cancellation token to use. - /// or is null. - public virtual Response AddTag(string key, string value, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(key, nameof(key)); - Argument.AssertNotNull(value, nameof(value)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.AddTag"); - scope.Start(); - try - { - if (CanUseTagResource(cancellationToken: cancellationToken)) - { - var originalTags = GetTagResource().Get(cancellationToken); - originalTags.Value.Data.TagValues[key] = value; - GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken); - var originalResponse = _resourceGroupRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken); - return Response.FromValue(new ResourceGroupResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - else - { - var current = Get(cancellationToken: cancellationToken).Value.Data; - var patch = new ResourceGroupPatch(); - foreach (var tag in current.Tags) - { - patch.Tags.Add(tag); - } - patch.Tags[key] = value; - var result = Update(patch, cancellationToken: cancellationToken); - return result; - } - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Replace the tags on the resource with the given set. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The set of tags to use as replacement. - /// The cancellation token to use. - /// is null. - public virtual async Task> SetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(tags, nameof(tags)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.SetTags"); - scope.Start(); - try - { - if (await CanUseTagResourceAsync(cancellationToken: cancellationToken).ConfigureAwait(false)) - { - await GetTagResource().DeleteAsync(WaitUntil.Completed, cancellationToken: cancellationToken).ConfigureAwait(false); - var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false); - originalTags.Value.Data.TagValues.ReplaceWith(tags); - await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false); - var originalResponse = await _resourceGroupRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new ResourceGroupResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - else - { - var current = (await GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false)).Value.Data; - var patch = new ResourceGroupPatch(); - patch.Tags.ReplaceWith(tags); - var result = await UpdateAsync(patch, cancellationToken: cancellationToken).ConfigureAwait(false); - return result; - } - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Replace the tags on the resource with the given set. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The set of tags to use as replacement. - /// The cancellation token to use. - /// is null. - public virtual Response SetTags(IDictionary tags, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(tags, nameof(tags)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.SetTags"); - scope.Start(); - try - { - if (CanUseTagResource(cancellationToken: cancellationToken)) - { - GetTagResource().Delete(WaitUntil.Completed, cancellationToken: cancellationToken); - var originalTags = GetTagResource().Get(cancellationToken); - originalTags.Value.Data.TagValues.ReplaceWith(tags); - GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken); - var originalResponse = _resourceGroupRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken); - return Response.FromValue(new ResourceGroupResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - else - { - var current = Get(cancellationToken: cancellationToken).Value.Data; - var patch = new ResourceGroupPatch(); - patch.Tags.ReplaceWith(tags); - var result = Update(patch, cancellationToken: cancellationToken); - return result; - } - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Removes a tag by key from the resource. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The key for the tag. - /// The cancellation token to use. - /// is null. - public virtual async Task> RemoveTagAsync(string key, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(key, nameof(key)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.RemoveTag"); - scope.Start(); - try - { - if (await CanUseTagResourceAsync(cancellationToken: cancellationToken).ConfigureAwait(false)) - { - var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false); - originalTags.Value.Data.TagValues.Remove(key); - await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false); - var originalResponse = await _resourceGroupRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new ResourceGroupResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - else - { - var current = (await GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false)).Value.Data; - var patch = new ResourceGroupPatch(); - foreach (var tag in current.Tags) - { - patch.Tags.Add(tag); - } - patch.Tags.Remove(key); - var result = await UpdateAsync(patch, cancellationToken: cancellationToken).ConfigureAwait(false); - return result; - } - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Removes a tag by key from the resource. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The key for the tag. - /// The cancellation token to use. - /// is null. - public virtual Response RemoveTag(string key, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(key, nameof(key)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.RemoveTag"); - scope.Start(); - try - { - if (CanUseTagResource(cancellationToken: cancellationToken)) - { - var originalTags = GetTagResource().Get(cancellationToken); - originalTags.Value.Data.TagValues.Remove(key); - GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken); - var originalResponse = _resourceGroupRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken); - return Response.FromValue(new ResourceGroupResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - else - { - var current = Get(cancellationToken: cancellationToken).Value.Data; - var patch = new ResourceGroupPatch(); - foreach (var tag in current.Tags) - { - patch.Tags.Add(tag); - } - patch.Tags.Remove(key); - var result = Update(patch, cancellationToken: cancellationToken); - return result; - } - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceManagerModelFactory.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceManagerModelFactory.cs deleted file mode 100644 index c17962de61..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceManagerModelFactory.cs +++ /dev/null @@ -1,764 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Linq; -using Azure.Core; -using Azure.ResourceManager.Resources; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Models -{ - /// Model factory for models. - public static partial class ResourceManagerModelFactory - { - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The location of the policy assignment. Only required when utilizing managed identity. - /// The managed identity associated with the policy assignment. Current supported identity types: None, SystemAssigned, UserAssigned. - /// The display name of the policy assignment. - /// The ID of the policy definition or policy set definition being assigned. - /// The scope for the policy assignment. - /// The policy's excluded scopes. - /// The parameter values for the assigned policy rule. The keys are the parameter names. - /// This message will be part of response in case of policy violation. - /// The policy assignment metadata. Metadata is an open ended object and is typically a collection of key value pairs. - /// The policy assignment enforcement mode. Possible values are Default and DoNotEnforce. - /// The messages that describe why a resource is non-compliant with the policy. - /// The resource selector list to filter policies by resource properties. - /// The policy property value override. - /// A new instance for mocking. - public static PolicyAssignmentData PolicyAssignmentData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, AzureLocation? location = null, ManagedServiceIdentity managedIdentity = null, string displayName = null, string policyDefinitionId = null, string scope = null, IEnumerable excludedScopes = null, IDictionary parameters = null, string description = null, BinaryData metadata = null, EnforcementMode? enforcementMode = null, IEnumerable nonComplianceMessages = null, IEnumerable resourceSelectors = null, IEnumerable overrides = null) - { - excludedScopes ??= new List(); - parameters ??= new Dictionary(); - nonComplianceMessages ??= new List(); - resourceSelectors ??= new List(); - overrides ??= new List(); - - return new PolicyAssignmentData( - id, - name, - resourceType, - systemData, - location, - managedIdentity, - displayName, - policyDefinitionId, - scope, - excludedScopes?.ToList(), - parameters, - description, - metadata, - enforcementMode, - nonComplianceMessages?.ToList(), - resourceSelectors?.ToList(), - overrides?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static. - /// The policy definition mode. Some examples are All, Indexed, Microsoft.KeyVault.Data. - /// The display name of the policy definition. - /// The policy definition description. - /// The policy rule. - /// The policy definition metadata. Metadata is an open ended object and is typically a collection of key value pairs. - /// The parameter definitions for parameters used in the policy rule. The keys are the parameter names. - /// A new instance for mocking. - public static PolicyDefinitionData PolicyDefinitionData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, PolicyType? policyType = null, string mode = null, string displayName = null, string description = null, BinaryData policyRule = null, BinaryData metadata = null, IDictionary parameters = null) - { - parameters ??= new Dictionary(); - - return new PolicyDefinitionData( - id, - name, - resourceType, - systemData, - policyType, - mode, - displayName, - description, - policyRule, - metadata, - parameters, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static. - /// The display name of the policy set definition. - /// The policy set definition description. - /// The policy set definition metadata. Metadata is an open ended object and is typically a collection of key value pairs. - /// The policy set definition parameters that can be used in policy definition references. - /// An array of policy definition references. - /// The metadata describing groups of policy definition references within the policy set definition. - /// A new instance for mocking. - public static PolicySetDefinitionData PolicySetDefinitionData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, PolicyType? policyType = null, string displayName = null, string description = null, BinaryData metadata = null, IDictionary parameters = null, IEnumerable policyDefinitions = null, IEnumerable policyDefinitionGroups = null) - { - parameters ??= new Dictionary(); - policyDefinitions ??= new List(); - policyDefinitionGroups ??= new List(); - - return new PolicySetDefinitionData( - id, - name, - resourceType, - systemData, - policyType, - displayName, - description, - metadata, - parameters, - policyDefinitions?.ToList(), - policyDefinitionGroups?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The list of namespaces for the data policy manifest. - /// The policy mode of the data policy manifest. - /// A value indicating whether policy mode is allowed only in built-in definitions. - /// An array of resource type aliases. - /// The effect definition. - /// The non-alias field accessor values that can be used in the policy rule. - /// The standard resource functions (subscription and/or resourceGroup). - /// An array of data manifest custom resource definition. - /// A new instance for mocking. - public static DataPolicyManifestData DataPolicyManifestData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, IEnumerable namespaces = null, string policyMode = null, bool? isBuiltInOnly = null, IEnumerable resourceTypeAliases = null, IEnumerable effects = null, IEnumerable fieldValues = null, IEnumerable standard = null, IEnumerable customDefinitions = null) - { - namespaces ??= new List(); - resourceTypeAliases ??= new List(); - effects ??= new List(); - fieldValues ??= new List(); - standard ??= new List(); - customDefinitions ??= new List(); - - return new DataPolicyManifestData( - id, - name, - resourceType, - systemData, - namespaces?.ToList(), - policyMode, - isBuiltInOnly, - resourceTypeAliases?.ToList(), - effects?.ToList(), - fieldValues?.ToList(), - standard?.ToList(), - customDefinitions?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The resource type name. - /// The aliases for property names. - /// A new instance for mocking. - public static ResourceTypeAliases ResourceTypeAliases(string resourceType = null, IEnumerable aliases = null) - { - aliases ??= new List(); - - return new ResourceTypeAliases(resourceType, aliases?.ToList(), serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The alias name. - /// The paths for an alias. - /// The type of the alias. - /// The default path for an alias. - /// The default pattern for an alias. - /// The default alias path metadata. Applies to the default path and to any alias path that doesn't have metadata. - /// A new instance for mocking. - public static ResourceTypeAlias ResourceTypeAlias(string name = null, IEnumerable paths = null, ResourceTypeAliasType? aliasType = null, string defaultPath = null, ResourceTypeAliasPattern defaultPattern = null, ResourceTypeAliasPathMetadata defaultMetadata = null) - { - paths ??= new List(); - - return new ResourceTypeAlias( - name, - paths?.ToList(), - aliasType, - defaultPath, - defaultPattern, - defaultMetadata, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The path of an alias. - /// The API versions. - /// The pattern for an alias path. - /// The metadata of the alias path. If missing, fall back to the default metadata of the alias. - /// A new instance for mocking. - public static ResourceTypeAliasPath ResourceTypeAliasPath(string path = null, IEnumerable apiVersions = null, ResourceTypeAliasPattern pattern = null, ResourceTypeAliasPathMetadata metadata = null) - { - apiVersions ??= new List(); - - return new ResourceTypeAliasPath(path, apiVersions?.ToList(), pattern, metadata, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The alias pattern phrase. - /// The alias pattern variable. - /// The type of alias pattern. - /// A new instance for mocking. - public static ResourceTypeAliasPattern ResourceTypeAliasPattern(string phrase = null, string variable = null, ResourceTypeAliasPatternType? patternType = null) - { - return new ResourceTypeAliasPattern(phrase, variable, patternType, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The type of the token that the alias path is referring to. - /// The attributes of the token that the alias path is referring to. - /// A new instance for mocking. - public static ResourceTypeAliasPathMetadata ResourceTypeAliasPathMetadata(ResourceTypeAliasPathTokenType? tokenType = null, ResourceTypeAliasPathAttributes? attributes = null) - { - return new ResourceTypeAliasPathMetadata(tokenType, attributes, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The data effect name. - /// The data effect details schema. - /// A new instance for mocking. - public static DataPolicyManifestEffect DataPolicyManifestEffect(string name = null, BinaryData detailsSchema = null) - { - return new DataPolicyManifestEffect(name, detailsSchema, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The function name as it will appear in the policy rule. eg - 'vault'. - /// The fully qualified control plane resource type that this function represents. eg - 'Microsoft.KeyVault/vaults'. - /// The top-level properties that can be selected on the function's output. eg - [ "name", "location" ] if vault().name and vault().location are supported. - /// A value indicating whether the custom properties within the property bag are allowed. Needs api-version to be specified in the policy rule eg - vault('2019-06-01'). - /// A new instance for mocking. - public static DataManifestCustomResourceFunctionDefinition DataManifestCustomResourceFunctionDefinition(string name = null, ResourceType? fullyQualifiedResourceType = null, IEnumerable defaultProperties = null, bool? allowCustomProperties = null) - { - defaultProperties ??= new List(); - - return new DataManifestCustomResourceFunctionDefinition(name, fullyQualifiedResourceType, defaultProperties?.ToList(), allowCustomProperties, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The level of the lock. Possible values are: NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users are able to read and modify the resources, but not delete. ReadOnly means authorized users can only read from a resource, but they can't modify or delete it. - /// Notes about the lock. Maximum of 512 characters. - /// The owners of the lock. - /// A new instance for mocking. - public static ManagementLockData ManagementLockData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, ManagementLockLevel level = default, string notes = null, IEnumerable owners = null) - { - owners ??= new List(); - - return new ManagementLockData( - id, - name, - resourceType, - systemData, - level, - notes, - owners?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The provider ID. - /// The namespace of the resource provider. - /// The registration state of the resource provider. - /// The registration policy of the resource provider. - /// The collection of provider resource types. - /// The provider authorization consent state. - /// A new instance for mocking. - public static ResourceProviderData ResourceProviderData(ResourceIdentifier id = null, string @namespace = null, string registrationState = null, string registrationPolicy = null, IEnumerable resourceTypes = null, ProviderAuthorizationConsentState? providerAuthorizationConsentState = null) - { - resourceTypes ??= new List(); - - return new ResourceProviderData( - id, - @namespace, - registrationState, - registrationPolicy, - resourceTypes?.ToList(), - providerAuthorizationConsentState, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The resource type. - /// The collection of locations where this resource type can be created. - /// The location mappings that are supported by this resource type. - /// The aliases that are supported by this resource type. - /// The API version. - /// The default API version. - /// - /// The API profiles for the resource provider. - /// The additional capabilities offered by this resource type. - /// The properties. - /// A new instance for mocking. - public static ProviderResourceType ProviderResourceType(string resourceType = null, IEnumerable locations = null, IEnumerable locationMappings = null, IEnumerable aliases = null, IEnumerable apiVersions = null, string defaultApiVersion = null, IEnumerable zoneMappings = null, IEnumerable apiProfiles = null, string capabilities = null, IReadOnlyDictionary properties = null) - { - locations ??= new List(); - locationMappings ??= new List(); - aliases ??= new List(); - apiVersions ??= new List(); - zoneMappings ??= new List(); - apiProfiles ??= new List(); - properties ??= new Dictionary(); - - return new ProviderResourceType( - resourceType, - locations?.ToList(), - locationMappings?.ToList(), - aliases?.ToList(), - apiVersions?.ToList(), - defaultApiVersion, - zoneMappings?.ToList(), - apiProfiles?.ToList(), - capabilities, - properties, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The azure location. - /// The extended location type. - /// The extended locations for the azure location. - /// A new instance for mocking. - public static ProviderExtendedLocation ProviderExtendedLocation(AzureLocation? location = null, string providerExtendedLocationType = null, IEnumerable extendedLocations = null) - { - extendedLocations ??= new List(); - - return new ProviderExtendedLocation(location, providerExtendedLocationType, extendedLocations?.ToList(), serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The location of the zone mapping. - /// - /// A new instance for mocking. - public static ZoneMapping ZoneMapping(AzureLocation? location = null, IEnumerable zones = null) - { - zones ??= new List(); - - return new ZoneMapping(location, zones?.ToList(), serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The profile version. - /// The API version. - /// A new instance for mocking. - public static ApiProfile ApiProfile(string profileVersion = null, string apiVersion = null) - { - return new ApiProfile(profileVersion, apiVersion, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The application id. - /// Role definition properties. - /// Role definition properties. - /// The provider authorization consent state. - /// A new instance for mocking. - public static ProviderPermission ProviderPermission(string applicationId = null, AzureRoleDefinition roleDefinition = null, AzureRoleDefinition managedByRoleDefinition = null, ProviderAuthorizationConsentState? providerAuthorizationConsentState = null) - { - return new ProviderPermission(applicationId, roleDefinition, managedByRoleDefinition, providerAuthorizationConsentState, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The role definition ID. - /// The role definition name. - /// If this is a service role. - /// Role definition permissions. - /// Role definition assignable scopes. - /// A new instance for mocking. - public static AzureRoleDefinition AzureRoleDefinition(string id = null, string name = null, bool? isServiceRole = null, IEnumerable permissions = null, IEnumerable scopes = null) - { - permissions ??= new List(); - scopes ??= new List(); - - return new AzureRoleDefinition( - id, - name, - isServiceRole, - permissions?.ToList(), - scopes?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// Allowed actions. - /// Denied actions. - /// Allowed Data actions. - /// Denied Data actions. - /// A new instance for mocking. - public static Permission Permission(IEnumerable allowedActions = null, IEnumerable deniedActions = null, IEnumerable allowedDataActions = null, IEnumerable deniedDataActions = null) - { - allowedActions ??= new List(); - deniedActions ??= new List(); - allowedDataActions ??= new List(); - deniedDataActions ??= new List(); - - return new Permission(allowedActions?.ToList(), deniedActions?.ToList(), allowedDataActions?.ToList(), deniedDataActions?.ToList(), serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The namespace of the resource provider. - /// The collection of provider resource types. - /// A new instance for mocking. - public static TenantResourceProvider TenantResourceProvider(string @namespace = null, IEnumerable resourceTypes = null) - { - resourceTypes ??= new List(); - - return new TenantResourceProvider(@namespace, resourceTypes?.ToList(), serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The tags. - /// The location. - /// Resource extended location. - /// The plan of the resource. - /// The resource properties. - /// The kind of the resource. - /// ID of the resource that manages this resource. - /// The SKU of the resource. - /// The identity of the resource. - /// The created time of the resource. This is only present if requested via the $expand query parameter. - /// The changed time of the resource. This is only present if requested via the $expand query parameter. - /// The provisioning state of the resource. This is only present if requested via the $expand query parameter. - /// A new instance for mocking. - public static GenericResourceData GenericResourceData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, IDictionary tags = null, AzureLocation location = default, ExtendedLocation extendedLocation = null, ArmPlan plan = null, BinaryData properties = null, string kind = null, string managedBy = null, ResourcesSku sku = null, ManagedServiceIdentity identity = null, DateTimeOffset? createdOn = null, DateTimeOffset? changedOn = null, string provisioningState = null) - { - tags ??= new Dictionary(); - - return new GenericResourceData( - id, - name, - resourceType, - systemData, - tags, - location, - extendedLocation, - serializedAdditionalRawData: null, - plan, - properties, - kind, - managedBy, - sku, - identity, - createdOn, - changedOn, - provisioningState); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The tags. - /// The location. - /// Resource extended location. - /// A new instance for mocking. - public static TrackedResourceExtendedData TrackedResourceExtendedData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, IDictionary tags = null, AzureLocation location = default, ExtendedLocation extendedLocation = null) - { - tags ??= new Dictionary(); - - return new TrackedResourceExtendedData( - id, - name, - resourceType, - systemData, - tags, - location, - extendedLocation, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The tags. - /// The location. - /// The resource group properties. - /// The ID of the resource that manages this resource group. - /// A new instance for mocking. - public static ResourceGroupData ResourceGroupData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, IDictionary tags = null, AzureLocation location = default, string resourceGroupProvisioningState = null, string managedBy = null) - { - tags ??= new Dictionary(); - - return new ResourceGroupData( - id, - name, - resourceType, - systemData, - tags, - location, - resourceGroupProvisioningState != null ? new ResourceGroupProperties(resourceGroupProvisioningState, serializedAdditionalRawData: null) : null, - managedBy, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The template content. - /// The template export error. - /// A new instance for mocking. - public static ResourceGroupExportResult ResourceGroupExportResult(BinaryData template = null, ResponseError error = null) - { - return new ResourceGroupExportResult(template, error, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The tag value ID. - /// The tag value. - /// The tag value count. - /// A new instance for mocking. - public static PredefinedTagValue PredefinedTagValue(string id = null, string tagValue = null, PredefinedTagCount count = null) - { - return new PredefinedTagValue(id, tagValue, count, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// Type of count. - /// Value of count. - /// A new instance for mocking. - public static PredefinedTagCount PredefinedTagCount(string predefinedTagCountType = null, int? value = null) - { - return new PredefinedTagCount(predefinedTagCountType, value, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The tag name ID. - /// The tag name. - /// The total number of resources that use the resource tag. When a tag is initially created and has no associated resources, the value is 0. - /// The list of tag values. - /// A new instance for mocking. - public static PredefinedTag PredefinedTag(string id = null, string tagName = null, PredefinedTagCount count = null, IEnumerable values = null) - { - values ??= new List(); - - return new PredefinedTag(id, tagName, count, values?.ToList(), serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The set of tags. - /// A new instance for mocking. - public static TagResourceData TagResourceData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, IDictionary tagValues = null) - { - tagValues ??= new Dictionary(); - - return new TagResourceData( - id, - name, - resourceType, - systemData, - tagValues != null ? new Tag(tagValues, serializedAdditionalRawData: null) : null, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The fully qualified ID of the location. For example, /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74/locations/westus. - /// The subscription ID. - /// The location name. - /// The location type. - /// The display name of the location. - /// The display name of the location and its region. - /// Metadata of the location, such as lat/long, paired region, and others. - /// The availability zone mappings for this region. - /// A new instance for mocking. - public static LocationExpanded LocationExpanded(string id = null, string subscriptionId = null, string name = null, LocationType? locationType = null, string displayName = null, string regionalDisplayName = null, LocationMetadata metadata = null, IEnumerable availabilityZoneMappings = null) - { - availabilityZoneMappings ??= new List(); - - return new LocationExpanded( - id, - subscriptionId, - name, - locationType, - displayName, - regionalDisplayName, - metadata, - availabilityZoneMappings?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The type of the region. - /// The category of the region. - /// The geography of the location. - /// The geography group of the location. - /// The longitude of the location. - /// The latitude of the location. - /// The physical location of the Azure location. - /// The regions paired to this region. - /// The home location of an edge zone. - /// A new instance for mocking. - public static LocationMetadata LocationMetadata(RegionType? regionType = null, RegionCategory? regionCategory = null, string geography = null, string geographyGroup = null, double? longitude = null, double? latitude = null, string physicalLocation = null, IEnumerable pairedRegions = null, string homeLocation = null) - { - pairedRegions ??= new List(); - - return new LocationMetadata( - regionType, - regionCategory, - geography, - geographyGroup, - longitude, - latitude, - physicalLocation, - pairedRegions?.ToList(), - homeLocation, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The name of the paired region. - /// The fully qualified ID of the location. For example, /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74/locations/westus. - /// The subscription ID. - /// A new instance for mocking. - public static PairedRegion PairedRegion(string name = null, string id = null, string subscriptionId = null) - { - return new PairedRegion(name, id, subscriptionId, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The logical zone id for the availability zone. - /// The fully qualified physical zone id of availability zone to which logical zone id is mapped to. - /// A new instance for mocking. - public static AvailabilityZoneMappings AvailabilityZoneMappings(string logicalZone = null, string physicalZone = null) - { - return new AvailabilityZoneMappings(logicalZone, physicalZone, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The fully qualified ID for the subscription. For example, /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74. - /// The subscription ID. - /// The subscription display name. - /// The subscription tenant ID. - /// The subscription state. Possible values are Enabled, Warned, PastDue, Disabled, and Deleted. - /// The subscription policies. - /// The authorization source of the request. Valid values are one or more combinations of Legacy, RoleBased, Bypassed, Direct and Management. For example, 'Legacy, RoleBased'. - /// An array containing the tenants managing the subscription. - /// The tags attached to the subscription. - /// A new instance for mocking. - public static SubscriptionData SubscriptionData(ResourceIdentifier id = null, string subscriptionId = null, string displayName = null, Guid? tenantId = null, SubscriptionState? state = null, SubscriptionPolicies subscriptionPolicies = null, string authorizationSource = null, IEnumerable managedByTenants = null, IReadOnlyDictionary tags = null) - { - managedByTenants ??= new List(); - tags ??= new Dictionary(); - - return new SubscriptionData( - id, - subscriptionId, - displayName, - tenantId, - state, - subscriptionPolicies, - authorizationSource, - managedByTenants?.ToList(), - tags, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The subscription location placement ID. The ID indicates which regions are visible for a subscription. For example, a subscription with a location placement Id of Public_2014-09-01 has access to Azure public regions. - /// The subscription quota ID. - /// The subscription spending limit. - /// A new instance for mocking. - public static SubscriptionPolicies SubscriptionPolicies(string locationPlacementId = null, string quotaId = null, SpendingLimit? spendingLimit = null) - { - return new SubscriptionPolicies(locationPlacementId, quotaId, spendingLimit, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The tenant ID of the managing tenant. This is a GUID. - /// A new instance for mocking. - public static ManagedByTenant ManagedByTenant(Guid? tenantId = null) - { - return new ManagedByTenant(tenantId, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The fully qualified ID of the tenant. For example, /tenants/8d65815f-a5b6-402f-9298-045155da7d74. - /// The tenant ID. For example, 8d65815f-a5b6-402f-9298-045155da7d74. - /// Category of the tenant. - /// Country/region name of the address for the tenant. - /// Country/region abbreviation for the tenant. - /// The display name of the tenant. - /// The list of domains for the tenant. - /// The default domain for the tenant. - /// The tenant type. Only available for 'Home' tenant category. - /// The tenant's branding logo URL. Only available for 'Home' tenant category. - /// A new instance for mocking. - public static TenantData TenantData(string id = null, Guid? tenantId = null, TenantCategory? tenantCategory = null, string country = null, string countryCode = null, string displayName = null, IEnumerable domains = null, string defaultDomain = null, string tenantType = null, Uri tenantBrandingLogoUri = null) - { - domains ??= new List(); - - return new TenantData( - id, - tenantId, - tenantCategory, - country, - countryCode, - displayName, - domains?.ToList(), - defaultDomain, - tenantType, - tenantBrandingLogoUri, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// Name of Resource. - /// Type of Resource. - /// Is the resource name Allowed or Reserved. - /// A new instance for mocking. - public static ResourceNameValidationResult ResourceNameValidationResult(string name = null, ResourceType? resourceType = null, ResourceNameValidationStatus? status = null) - { - return new ResourceNameValidationResult(name, resourceType, status, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// Properties of the previewed feature. - /// A new instance for mocking. - public static FeatureData FeatureData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, string featureState = null) - { - return new FeatureData( - id, - name, - resourceType, - systemData, - featureState != null ? new FeatureProperties(featureState, serializedAdditionalRawData: null) : null, - serializedAdditionalRawData: null); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderCollection.cs deleted file mode 100644 index 5915ae4051..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderCollection.cs +++ /dev/null @@ -1,389 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetResourceProviders method from an instance of . - /// - public partial class ResourceProviderCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _resourceProviderProvidersClientDiagnostics; - private readonly ProvidersRestOperations _resourceProviderProvidersRestClient; - - /// Initializes a new instance of the class for mocking. - protected ResourceProviderCollection() - { - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != SubscriptionResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, SubscriptionResource.ResourceType), nameof(id)); - } - - /// - /// Gets the specified resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderCollection.Get"); - scope.Start(); - try - { - var response = await _resourceProviderProvidersRestClient.GetAsync(Id.SubscriptionId, resourceProviderNamespace, expand, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets the specified resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderCollection.Get"); - scope.Start(); - try - { - var response = _resourceProviderProvidersRestClient.Get(Id.SubscriptionId, resourceProviderNamespace, expand, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets all resource providers for a subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers - /// - /// - /// Operation Id - /// Providers_List - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string expand = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _resourceProviderProvidersRestClient.CreateListRequest(Id.SubscriptionId, expand); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _resourceProviderProvidersRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, expand); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new ResourceProviderResource(Client, ResourceProviderData.DeserializeResourceProviderData(e)), _resourceProviderProvidersClientDiagnostics, Pipeline, "ResourceProviderCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Gets all resource providers for a subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers - /// - /// - /// Operation Id - /// Providers_List - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string expand = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _resourceProviderProvidersRestClient.CreateListRequest(Id.SubscriptionId, expand); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _resourceProviderProvidersRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, expand); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new ResourceProviderResource(Client, ResourceProviderData.DeserializeResourceProviderData(e)), _resourceProviderProvidersClientDiagnostics, Pipeline, "ResourceProviderCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderCollection.Exists"); - scope.Start(); - try - { - var response = await _resourceProviderProvidersRestClient.GetAsync(Id.SubscriptionId, resourceProviderNamespace, expand, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderCollection.Exists"); - scope.Start(); - try - { - var response = _resourceProviderProvidersRestClient.Get(Id.SubscriptionId, resourceProviderNamespace, expand, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _resourceProviderProvidersRestClient.GetAsync(Id.SubscriptionId, resourceProviderNamespace, expand, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderCollection.GetIfExists"); - scope.Start(); - try - { - var response = _resourceProviderProvidersRestClient.Get(Id.SubscriptionId, resourceProviderNamespace, expand, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderData.Serialization.cs deleted file mode 100644 index 98cd1f22ff..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderData.Serialization.cs +++ /dev/null @@ -1,355 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class ResourceProviderData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceProviderData)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (Optional.IsDefined(Namespace)) - { - writer.WritePropertyName("namespace"u8); - writer.WriteStringValue(Namespace); - } - if (options.Format != "W" && Optional.IsDefined(RegistrationState)) - { - writer.WritePropertyName("registrationState"u8); - writer.WriteStringValue(RegistrationState); - } - if (options.Format != "W" && Optional.IsDefined(RegistrationPolicy)) - { - writer.WritePropertyName("registrationPolicy"u8); - writer.WriteStringValue(RegistrationPolicy); - } - if (options.Format != "W" && Optional.IsCollectionDefined(ResourceTypes)) - { - writer.WritePropertyName("resourceTypes"u8); - writer.WriteStartArray(); - foreach (var item in ResourceTypes) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(ProviderAuthorizationConsentState)) - { - writer.WritePropertyName("providerAuthorizationConsentState"u8); - writer.WriteStringValue(ProviderAuthorizationConsentState.Value.ToString()); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - ResourceProviderData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceProviderData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceProviderData(document.RootElement, options); - } - - internal static ResourceProviderData DeserializeResourceProviderData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string @namespace = default; - string registrationState = default; - string registrationPolicy = default; - IReadOnlyList resourceTypes = default; - ProviderAuthorizationConsentState? providerAuthorizationConsentState = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("namespace"u8)) - { - @namespace = property.Value.GetString(); - continue; - } - if (property.NameEquals("registrationState"u8)) - { - registrationState = property.Value.GetString(); - continue; - } - if (property.NameEquals("registrationPolicy"u8)) - { - registrationPolicy = property.Value.GetString(); - continue; - } - if (property.NameEquals("resourceTypes"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ProviderResourceType.DeserializeProviderResourceType(item, options)); - } - resourceTypes = array; - continue; - } - if (property.NameEquals("providerAuthorizationConsentState"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - providerAuthorizationConsentState = new ProviderAuthorizationConsentState(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceProviderData( - id, - @namespace, - registrationState, - registrationPolicy, - resourceTypes ?? new ChangeTrackingList(), - providerAuthorizationConsentState, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Namespace), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" namespace: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Namespace)) - { - builder.Append(" namespace: "); - if (Namespace.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Namespace}'''"); - } - else - { - builder.AppendLine($"'{Namespace}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(RegistrationState), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" registrationState: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(RegistrationState)) - { - builder.Append(" registrationState: "); - if (RegistrationState.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{RegistrationState}'''"); - } - else - { - builder.AppendLine($"'{RegistrationState}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(RegistrationPolicy), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" registrationPolicy: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(RegistrationPolicy)) - { - builder.Append(" registrationPolicy: "); - if (RegistrationPolicy.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{RegistrationPolicy}'''"); - } - else - { - builder.AppendLine($"'{RegistrationPolicy}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ResourceTypes), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" resourceTypes: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ResourceTypes)) - { - if (ResourceTypes.Any()) - { - builder.Append(" resourceTypes: "); - builder.AppendLine("["); - foreach (var item in ResourceTypes) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " resourceTypes: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ProviderAuthorizationConsentState), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" providerAuthorizationConsentState: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ProviderAuthorizationConsentState)) - { - builder.Append(" providerAuthorizationConsentState: "); - builder.AppendLine($"'{ProviderAuthorizationConsentState.Value.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceProviderData)} does not support writing '{options.Format}' format."); - } - } - - ResourceProviderData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceProviderData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceProviderData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderData.cs deleted file mode 100644 index e18d3655a2..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderData.cs +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the ResourceProvider data model. - /// Resource provider information. - /// - public partial class ResourceProviderData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The provider ID. - /// The namespace of the resource provider. - /// The registration state of the resource provider. - /// The registration policy of the resource provider. - /// The collection of provider resource types. - /// The provider authorization consent state. - /// Keeps track of any properties unknown to the library. - internal ResourceProviderData(ResourceIdentifier id, string @namespace, string registrationState, string registrationPolicy, IReadOnlyList resourceTypes, ProviderAuthorizationConsentState? providerAuthorizationConsentState, IDictionary serializedAdditionalRawData) - { - Id = id; - Namespace = @namespace; - RegistrationState = registrationState; - RegistrationPolicy = registrationPolicy; - ResourceTypes = resourceTypes; - ProviderAuthorizationConsentState = providerAuthorizationConsentState; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - /// The namespace of the resource provider. - [WirePath("namespace")] - public string Namespace { get; } - /// The registration state of the resource provider. - [WirePath("registrationState")] - public string RegistrationState { get; } - /// The registration policy of the resource provider. - [WirePath("registrationPolicy")] - public string RegistrationPolicy { get; } - /// The collection of provider resource types. - [WirePath("resourceTypes")] - public IReadOnlyList ResourceTypes { get; } - /// The provider authorization consent state. - [WirePath("providerAuthorizationConsentState")] - public ProviderAuthorizationConsentState? ProviderAuthorizationConsentState { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderResource.Serialization.cs deleted file mode 100644 index cff873e5de..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class ResourceProviderResource : IJsonModel - { - private static ResourceProviderData s_dataDeserializationInstance; - private static ResourceProviderData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - ResourceProviderData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - ResourceProviderData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderResource.cs deleted file mode 100644 index 1644e4e793..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/ResourceProviderResource.cs +++ /dev/null @@ -1,509 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a ResourceProvider along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetResourceProviderResource method. - /// Otherwise you can get one from its parent resource using the GetResourceProvider method. - /// - public partial class ResourceProviderResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The subscriptionId. - /// The resourceProviderNamespace. - public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceProviderNamespace) - { - var resourceId = $"/subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _resourceProviderProvidersClientDiagnostics; - private readonly ProvidersRestOperations _resourceProviderProvidersRestClient; - private readonly ClientDiagnostics _providerResourceTypesClientDiagnostics; - private readonly ProviderResourceTypesRestOperations _providerResourceTypesRestClient; - private readonly ResourceProviderData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Resources/providers"; - - /// Initializes a new instance of the class for mocking. - protected ResourceProviderResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal ResourceProviderResource(ArmClient client, ResourceProviderData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal ResourceProviderResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _resourceProviderProvidersClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string resourceProviderProvidersApiVersion); - _resourceProviderProvidersRestClient = new ProvidersRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, resourceProviderProvidersApiVersion); - _providerResourceTypesClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ProviderConstants.DefaultProviderNamespace, Diagnostics); - _providerResourceTypesRestClient = new ProviderResourceTypesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual ResourceProviderData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// Gets a collection of FeatureResources in the ResourceProvider. - /// An object representing collection of FeatureResources and their operations over a FeatureResource. - public virtual FeatureCollection GetFeatures() - { - return GetCachedClient(client => new FeatureCollection(client, Id)); - } - - /// - /// Gets the preview feature with the specified name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the feature to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetFeatureAsync(string featureName, CancellationToken cancellationToken = default) - { - return await GetFeatures().GetAsync(featureName, cancellationToken).ConfigureAwait(false); - } - - /// - /// Gets the preview feature with the specified name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the feature to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetFeature(string featureName, CancellationToken cancellationToken = default) - { - return GetFeatures().Get(featureName, cancellationToken); - } - - /// - /// Gets the specified resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - public virtual async Task> GetAsync(string expand = null, CancellationToken cancellationToken = default) - { - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderResource.Get"); - scope.Start(); - try - { - var response = await _resourceProviderProvidersRestClient.GetAsync(Id.SubscriptionId, Id.Provider, expand, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets the specified resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - public virtual Response Get(string expand = null, CancellationToken cancellationToken = default) - { - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderResource.Get"); - scope.Start(); - try - { - var response = _resourceProviderProvidersRestClient.Get(Id.SubscriptionId, Id.Provider, expand, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Unregisters a subscription from a resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/unregister - /// - /// - /// Operation Id - /// Providers_Unregister - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> UnregisterAsync(CancellationToken cancellationToken = default) - { - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderResource.Unregister"); - scope.Start(); - try - { - var response = await _resourceProviderProvidersRestClient.UnregisterAsync(Id.SubscriptionId, Id.Provider, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Unregisters a subscription from a resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/unregister - /// - /// - /// Operation Id - /// Providers_Unregister - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Unregister(CancellationToken cancellationToken = default) - { - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderResource.Unregister"); - scope.Start(); - try - { - var response = _resourceProviderProvidersRestClient.Unregister(Id.SubscriptionId, Id.Provider, cancellationToken); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Get the provider permissions. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/providerPermissions - /// - /// - /// Operation Id - /// Providers_ProviderPermissions - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable ProviderPermissionsAsync(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _resourceProviderProvidersRestClient.CreateProviderPermissionsRequest(Id.SubscriptionId, Id.Provider); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, null, e => ProviderPermission.DeserializeProviderPermission(e), _resourceProviderProvidersClientDiagnostics, Pipeline, "ResourceProviderResource.ProviderPermissions", "value", null, cancellationToken); - } - - /// - /// Get the provider permissions. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/providerPermissions - /// - /// - /// Operation Id - /// Providers_ProviderPermissions - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable ProviderPermissions(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _resourceProviderProvidersRestClient.CreateProviderPermissionsRequest(Id.SubscriptionId, Id.Provider); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, null, e => ProviderPermission.DeserializeProviderPermission(e), _resourceProviderProvidersClientDiagnostics, Pipeline, "ResourceProviderResource.ProviderPermissions", "value", null, cancellationToken); - } - - /// - /// Registers a subscription with a resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/register - /// - /// - /// Operation Id - /// Providers_Register - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The third party consent for S2S. - /// The cancellation token to use. - public virtual async Task> RegisterAsync(ProviderRegistrationContent content = null, CancellationToken cancellationToken = default) - { - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderResource.Register"); - scope.Start(); - try - { - var response = await _resourceProviderProvidersRestClient.RegisterAsync(Id.SubscriptionId, Id.Provider, content, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Registers a subscription with a resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/register - /// - /// - /// Operation Id - /// Providers_Register - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The third party consent for S2S. - /// The cancellation token to use. - public virtual Response Register(ProviderRegistrationContent content = null, CancellationToken cancellationToken = default) - { - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderResource.Register"); - scope.Start(); - try - { - var response = _resourceProviderProvidersRestClient.Register(Id.SubscriptionId, Id.Provider, content, cancellationToken); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// List the resource types for a specified resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/resourceTypes - /// - /// - /// Operation Id - /// ProviderResourceTypes_List - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetProviderResourceTypesAsync(string expand = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _providerResourceTypesRestClient.CreateListRequest(Id.SubscriptionId, Id.Provider, expand); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, null, e => ProviderResourceType.DeserializeProviderResourceType(e), _providerResourceTypesClientDiagnostics, Pipeline, "ResourceProviderResource.GetProviderResourceTypes", "value", null, cancellationToken); - } - - /// - /// List the resource types for a specified resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/resourceTypes - /// - /// - /// Operation Id - /// ProviderResourceTypes_List - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetProviderResourceTypes(string expand = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _providerResourceTypesRestClient.CreateListRequest(Id.SubscriptionId, Id.Provider, expand); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, null, e => ProviderResourceType.DeserializeProviderResourceType(e), _providerResourceTypesClientDiagnostics, Pipeline, "ResourceProviderResource.GetProviderResourceTypes", "value", null, cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/DataPolicyManifestsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/DataPolicyManifestsRestOperations.cs deleted file mode 100644 index b94f641cd7..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/DataPolicyManifestsRestOperations.cs +++ /dev/null @@ -1,265 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class DataPolicyManifestsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of DataPolicyManifestsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public DataPolicyManifestsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2020-09-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateGetByPolicyModeRequestUri(string policyMode) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/dataPolicyManifests/", false); - uri.AppendPath(policyMode, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetByPolicyModeRequest(string policyMode) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/dataPolicyManifests/", false); - uri.AppendPath(policyMode, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the data policy manifest with the given policy mode. - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetByPolicyModeAsync(string policyMode, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyMode, nameof(policyMode)); - - using var message = CreateGetByPolicyModeRequest(policyMode); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - DataPolicyManifestData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = DataPolicyManifestData.DeserializeDataPolicyManifestData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((DataPolicyManifestData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the data policy manifest with the given policy mode. - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response GetByPolicyMode(string policyMode, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyMode, nameof(policyMode)); - - using var message = CreateGetByPolicyModeRequest(policyMode); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - DataPolicyManifestData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = DataPolicyManifestData.DeserializeDataPolicyManifestData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((DataPolicyManifestData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri(string filter) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/dataPolicyManifests", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - return uri; - } - - internal HttpMessage CreateListRequest(string filter) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/dataPolicyManifests", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the data policy manifests that match the optional given $filter. Valid values for $filter are: "$filter=namespace eq '{0}'". If $filter is not provided, the unfiltered list includes all data policy manifests for data resource types. If $filter=namespace is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The filter to apply on the operation. Valid values for $filter are: "namespace eq '{value}'". If $filter is not provided, no filtering is performed. If $filter=namespace eq '{value}' is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The cancellation token to use. - public async Task> ListAsync(string filter = null, CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(filter); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - DataPolicyManifestListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = DataPolicyManifestListResult.DeserializeDataPolicyManifestListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the data policy manifests that match the optional given $filter. Valid values for $filter are: "$filter=namespace eq '{0}'". If $filter is not provided, the unfiltered list includes all data policy manifests for data resource types. If $filter=namespace is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The filter to apply on the operation. Valid values for $filter are: "namespace eq '{value}'". If $filter is not provided, no filtering is performed. If $filter=namespace eq '{value}' is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The cancellation token to use. - public Response List(string filter = null, CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(filter); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - DataPolicyManifestListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = DataPolicyManifestListResult.DeserializeDataPolicyManifestListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string filter) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string filter) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the data policy manifests that match the optional given $filter. Valid values for $filter are: "$filter=namespace eq '{0}'". If $filter is not provided, the unfiltered list includes all data policy manifests for data resource types. If $filter=namespace is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The URL to the next page of results. - /// The filter to apply on the operation. Valid values for $filter are: "namespace eq '{value}'". If $filter is not provided, no filtering is performed. If $filter=namespace eq '{value}' is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The cancellation token to use. - /// is null. - public async Task> ListNextPageAsync(string nextLink, string filter = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink, filter); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - DataPolicyManifestListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = DataPolicyManifestListResult.DeserializeDataPolicyManifestListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the data policy manifests that match the optional given $filter. Valid values for $filter are: "$filter=namespace eq '{0}'". If $filter is not provided, the unfiltered list includes all data policy manifests for data resource types. If $filter=namespace is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The URL to the next page of results. - /// The filter to apply on the operation. Valid values for $filter are: "namespace eq '{value}'". If $filter is not provided, no filtering is performed. If $filter=namespace eq '{value}' is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The cancellation token to use. - /// is null. - public Response ListNextPage(string nextLink, string filter = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink, filter); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - DataPolicyManifestListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = DataPolicyManifestListResult.DeserializeDataPolicyManifestListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/FeaturesRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/FeaturesRestOperations.cs deleted file mode 100644 index 6eda9037c4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/FeaturesRestOperations.cs +++ /dev/null @@ -1,643 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class FeaturesRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of FeaturesRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public FeaturesRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2021-07-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateListAllRequestUri(string subscriptionId) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/features", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListAllRequest(string subscriptionId) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/features", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json, text/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all the preview features that are available through AFEC for the subscription. - /// The ID of the target subscription. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListAllAsync(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListAllRequest(subscriptionId); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - FeatureOperationsListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = FeatureOperationsListResult.DeserializeFeatureOperationsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all the preview features that are available through AFEC for the subscription. - /// The ID of the target subscription. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response ListAll(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListAllRequest(subscriptionId); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - FeatureOperationsListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = FeatureOperationsListResult.DeserializeFeatureOperationsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri(string subscriptionId, string resourceProviderNamespace) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/features", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListRequest(string subscriptionId, string resourceProviderNamespace) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/features", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json, text/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all the preview features in a provider namespace that are available through AFEC for the subscription. - /// The ID of the target subscription. - /// The namespace of the resource provider for getting features. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> ListAsync(string subscriptionId, string resourceProviderNamespace, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateListRequest(subscriptionId, resourceProviderNamespace); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - FeatureOperationsListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = FeatureOperationsListResult.DeserializeFeatureOperationsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all the preview features in a provider namespace that are available through AFEC for the subscription. - /// The ID of the target subscription. - /// The namespace of the resource provider for getting features. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response List(string subscriptionId, string resourceProviderNamespace, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateListRequest(subscriptionId, resourceProviderNamespace); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - FeatureOperationsListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = FeatureOperationsListResult.DeserializeFeatureOperationsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetRequestUri(string subscriptionId, string resourceProviderNamespace, string featureName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/features/", false); - uri.AppendPath(featureName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetRequest(string subscriptionId, string resourceProviderNamespace, string featureName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/features/", false); - uri.AppendPath(featureName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json, text/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets the preview feature with the specified name. - /// The ID of the target subscription. - /// The resource provider namespace for the feature. - /// The name of the feature to get. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public async Task> GetAsync(string subscriptionId, string resourceProviderNamespace, string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var message = CreateGetRequest(subscriptionId, resourceProviderNamespace, featureName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - FeatureData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = FeatureData.DeserializeFeatureData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((FeatureData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets the preview feature with the specified name. - /// The ID of the target subscription. - /// The resource provider namespace for the feature. - /// The name of the feature to get. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public Response Get(string subscriptionId, string resourceProviderNamespace, string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var message = CreateGetRequest(subscriptionId, resourceProviderNamespace, featureName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - FeatureData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = FeatureData.DeserializeFeatureData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((FeatureData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateRegisterRequestUri(string subscriptionId, string resourceProviderNamespace, string featureName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/features/", false); - uri.AppendPath(featureName, true); - uri.AppendPath("/register", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateRegisterRequest(string subscriptionId, string resourceProviderNamespace, string featureName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/features/", false); - uri.AppendPath(featureName, true); - uri.AppendPath("/register", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json, text/json"); - _userAgent.Apply(message); - return message; - } - - /// Registers the preview feature for the subscription. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The name of the feature to register. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public async Task> RegisterAsync(string subscriptionId, string resourceProviderNamespace, string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var message = CreateRegisterRequest(subscriptionId, resourceProviderNamespace, featureName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - FeatureData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = FeatureData.DeserializeFeatureData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Registers the preview feature for the subscription. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The name of the feature to register. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public Response Register(string subscriptionId, string resourceProviderNamespace, string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var message = CreateRegisterRequest(subscriptionId, resourceProviderNamespace, featureName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - FeatureData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = FeatureData.DeserializeFeatureData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateUnregisterRequestUri(string subscriptionId, string resourceProviderNamespace, string featureName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/features/", false); - uri.AppendPath(featureName, true); - uri.AppendPath("/unregister", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateUnregisterRequest(string subscriptionId, string resourceProviderNamespace, string featureName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/features/", false); - uri.AppendPath(featureName, true); - uri.AppendPath("/unregister", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json, text/json"); - _userAgent.Apply(message); - return message; - } - - /// Unregisters the preview feature for the subscription. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The name of the feature to unregister. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public async Task> UnregisterAsync(string subscriptionId, string resourceProviderNamespace, string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var message = CreateUnregisterRequest(subscriptionId, resourceProviderNamespace, featureName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - FeatureData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = FeatureData.DeserializeFeatureData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Unregisters the preview feature for the subscription. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The name of the feature to unregister. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public Response Unregister(string subscriptionId, string resourceProviderNamespace, string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var message = CreateUnregisterRequest(subscriptionId, resourceProviderNamespace, featureName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - FeatureData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = FeatureData.DeserializeFeatureData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListAllNextPageRequestUri(string nextLink, string subscriptionId) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListAllNextPageRequest(string nextLink, string subscriptionId) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json, text/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all the preview features that are available through AFEC for the subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListAllNextPageAsync(string nextLink, string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListAllNextPageRequest(nextLink, subscriptionId); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - FeatureOperationsListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = FeatureOperationsListResult.DeserializeFeatureOperationsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all the preview features that are available through AFEC for the subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListAllNextPage(string nextLink, string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListAllNextPageRequest(nextLink, subscriptionId); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - FeatureOperationsListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = FeatureOperationsListResult.DeserializeFeatureOperationsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string subscriptionId, string resourceProviderNamespace) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string resourceProviderNamespace) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json, text/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all the preview features in a provider namespace that are available through AFEC for the subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The namespace of the resource provider for getting features. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> ListNextPageAsync(string nextLink, string subscriptionId, string resourceProviderNamespace, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceProviderNamespace); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - FeatureOperationsListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = FeatureOperationsListResult.DeserializeFeatureOperationsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all the preview features in a provider namespace that are available through AFEC for the subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The namespace of the resource provider for getting features. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response ListNextPage(string nextLink, string subscriptionId, string resourceProviderNamespace, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceProviderNamespace); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - FeatureOperationsListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = FeatureOperationsListResult.DeserializeFeatureOperationsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ManagementLocksRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ManagementLocksRestOperations.cs deleted file mode 100644 index 66b3dc6664..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ManagementLocksRestOperations.cs +++ /dev/null @@ -1,459 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class ManagementLocksRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of ManagementLocksRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public ManagementLocksRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2020-05-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateCreateOrUpdateByScopeRequestUri(string scope, string lockName, ManagementLockData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/locks/", false); - uri.AppendPath(lockName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateByScopeRequest(string scope, string lockName, ManagementLockData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/locks/", false); - uri.AppendPath(lockName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// Create or update a management lock by scope. - /// The scope for the lock. When providing a scope for the assignment, use '/subscriptions/{subscriptionId}' for subscriptions, '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' for resources. - /// The name of lock. - /// Create or update management lock parameters. - /// The cancellation token to use. - /// , or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> CreateOrUpdateByScopeAsync(string scope, string lockName, ManagementLockData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateByScopeRequest(scope, lockName, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 201: - { - ManagementLockData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementLockData.DeserializeManagementLockData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Create or update a management lock by scope. - /// The scope for the lock. When providing a scope for the assignment, use '/subscriptions/{subscriptionId}' for subscriptions, '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' for resources. - /// The name of lock. - /// Create or update management lock parameters. - /// The cancellation token to use. - /// , or is null. - /// is an empty string, and was expected to be non-empty. - public Response CreateOrUpdateByScope(string scope, string lockName, ManagementLockData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateByScopeRequest(scope, lockName, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 201: - { - ManagementLockData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementLockData.DeserializeManagementLockData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteByScopeRequestUri(string scope, string lockName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/locks/", false); - uri.AppendPath(lockName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteByScopeRequest(string scope, string lockName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/locks/", false); - uri.AppendPath(lockName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Delete a management lock by scope. - /// The scope for the lock. - /// The name of lock. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task DeleteByScopeAsync(string scope, string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var message = CreateDeleteByScopeRequest(scope, lockName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// Delete a management lock by scope. - /// The scope for the lock. - /// The name of lock. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response DeleteByScope(string scope, string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var message = CreateDeleteByScopeRequest(scope, lockName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetByScopeRequestUri(string scope, string lockName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/locks/", false); - uri.AppendPath(lockName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetByScopeRequest(string scope, string lockName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/locks/", false); - uri.AppendPath(lockName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Get a management lock by scope. - /// The scope for the lock. - /// The name of lock. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetByScopeAsync(string scope, string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var message = CreateGetByScopeRequest(scope, lockName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementLockData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementLockData.DeserializeManagementLockData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ManagementLockData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// Get a management lock by scope. - /// The scope for the lock. - /// The name of lock. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response GetByScope(string scope, string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var message = CreateGetByScopeRequest(scope, lockName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementLockData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementLockData.DeserializeManagementLockData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ManagementLockData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListByScopeRequestUri(string scope, string filter) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/locks", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListByScopeRequest(string scope, string filter) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/locks", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all the management locks for a scope. - /// The scope for the lock. When providing a scope for the assignment, use '/subscriptions/{subscriptionId}' for subscriptions, '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' for resources. - /// The filter to apply on the operation. - /// The cancellation token to use. - /// is null. - public async Task> ListByScopeAsync(string scope, string filter = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - - using var message = CreateListByScopeRequest(scope, filter); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementLockListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementLockListResult.DeserializeManagementLockListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all the management locks for a scope. - /// The scope for the lock. When providing a scope for the assignment, use '/subscriptions/{subscriptionId}' for subscriptions, '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' for resources. - /// The filter to apply on the operation. - /// The cancellation token to use. - /// is null. - public Response ListByScope(string scope, string filter = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - - using var message = CreateListByScopeRequest(scope, filter); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementLockListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementLockListResult.DeserializeManagementLockListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListByScopeNextPageRequestUri(string nextLink, string scope, string filter) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListByScopeNextPageRequest(string nextLink, string scope, string filter) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all the management locks for a scope. - /// The URL to the next page of results. - /// The scope for the lock. When providing a scope for the assignment, use '/subscriptions/{subscriptionId}' for subscriptions, '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' for resources. - /// The filter to apply on the operation. - /// The cancellation token to use. - /// or is null. - public async Task> ListByScopeNextPageAsync(string nextLink, string scope, string filter = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNull(scope, nameof(scope)); - - using var message = CreateListByScopeNextPageRequest(nextLink, scope, filter); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementLockListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementLockListResult.DeserializeManagementLockListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all the management locks for a scope. - /// The URL to the next page of results. - /// The scope for the lock. When providing a scope for the assignment, use '/subscriptions/{subscriptionId}' for subscriptions, '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' for resources. - /// The filter to apply on the operation. - /// The cancellation token to use. - /// or is null. - public Response ListByScopeNextPage(string nextLink, string scope, string filter = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNull(scope, nameof(scope)); - - using var message = CreateListByScopeNextPageRequest(nextLink, scope, filter); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementLockListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementLockListResult.DeserializeManagementLockListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicyAssignmentsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicyAssignmentsRestOperations.cs deleted file mode 100644 index 8437bfbc9f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicyAssignmentsRestOperations.cs +++ /dev/null @@ -1,1183 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class PolicyAssignmentsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of PolicyAssignmentsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public PolicyAssignmentsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2022-06-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateDeleteRequestUri(string scope, string policyAssignmentName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments/", false); - uri.AppendPath(policyAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteRequest(string scope, string policyAssignmentName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments/", false); - uri.AppendPath(policyAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation deletes a policy assignment, given its name and the scope it was created in. The scope of a policy assignment is the part of its ID preceding '/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. - /// The scope of the policy assignment. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - /// The name of the policy assignment to delete. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> DeleteAsync(string scope, string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var message = CreateDeleteRequest(scope, policyAssignmentName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentData.DeserializePolicyAssignmentData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 204: - return Response.FromValue((PolicyAssignmentData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation deletes a policy assignment, given its name and the scope it was created in. The scope of a policy assignment is the part of its ID preceding '/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. - /// The scope of the policy assignment. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - /// The name of the policy assignment to delete. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response Delete(string scope, string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var message = CreateDeleteRequest(scope, policyAssignmentName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentData.DeserializePolicyAssignmentData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 204: - return Response.FromValue((PolicyAssignmentData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateCreateRequestUri(string scope, string policyAssignmentName, PolicyAssignmentData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments/", false); - uri.AppendPath(policyAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateRequest(string scope, string policyAssignmentName, PolicyAssignmentData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments/", false); - uri.AppendPath(policyAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// The scope of the policy assignment. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - /// The name of the policy assignment. - /// Parameters for the policy assignment. - /// The cancellation token to use. - /// , or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> CreateAsync(string scope, string policyAssignmentName, PolicyAssignmentData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateRequest(scope, policyAssignmentName, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 201: - { - PolicyAssignmentData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentData.DeserializePolicyAssignmentData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// The scope of the policy assignment. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - /// The name of the policy assignment. - /// Parameters for the policy assignment. - /// The cancellation token to use. - /// , or is null. - /// is an empty string, and was expected to be non-empty. - public Response Create(string scope, string policyAssignmentName, PolicyAssignmentData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateRequest(scope, policyAssignmentName, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 201: - { - PolicyAssignmentData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentData.DeserializePolicyAssignmentData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetRequestUri(string scope, string policyAssignmentName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments/", false); - uri.AppendPath(policyAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetRequest(string scope, string policyAssignmentName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments/", false); - uri.AppendPath(policyAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a single policy assignment, given its name and the scope it was created at. - /// The scope of the policy assignment. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetAsync(string scope, string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var message = CreateGetRequest(scope, policyAssignmentName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentData.DeserializePolicyAssignmentData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicyAssignmentData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a single policy assignment, given its name and the scope it was created at. - /// The scope of the policy assignment. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response Get(string scope, string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var message = CreateGetRequest(scope, policyAssignmentName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentData.DeserializePolicyAssignmentData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicyAssignmentData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateUpdateRequestUri(string scope, string policyAssignmentName, PolicyAssignmentPatch patch) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments/", false); - uri.AppendPath(policyAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateUpdateRequest(string scope, string policyAssignmentName, PolicyAssignmentPatch patch) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Patch; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments/", false); - uri.AppendPath(policyAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(patch, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// This operation updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// The scope of the policy assignment. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - /// The name of the policy assignment. - /// Parameters for policy assignment patch request. - /// The cancellation token to use. - /// , or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> UpdateAsync(string scope, string policyAssignmentName, PolicyAssignmentPatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - Argument.AssertNotNull(patch, nameof(patch)); - - using var message = CreateUpdateRequest(scope, policyAssignmentName, patch); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentData.DeserializePolicyAssignmentData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// The scope of the policy assignment. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - /// The name of the policy assignment. - /// Parameters for policy assignment patch request. - /// The cancellation token to use. - /// , or is null. - /// is an empty string, and was expected to be non-empty. - public Response Update(string scope, string policyAssignmentName, PolicyAssignmentPatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - Argument.AssertNotNull(patch, nameof(patch)); - - using var message = CreateUpdateRequest(scope, policyAssignmentName, patch); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentData.DeserializePolicyAssignmentData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListForResourceGroupRequestUri(string subscriptionId, string resourceGroupName, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListForResourceGroupRequest(string subscriptionId, string resourceGroupName, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the list of all policy assignments associated with the given resource group in the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource group, including those that apply directly or apply from containing scopes, as well as any applied to resources contained within the resource group. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource group, which is everything in the unfiltered list except those applied to resources contained within the resource group. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource group. - /// The ID of the target subscription. - /// The name of the resource group that contains policy assignments. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> ListForResourceGroupAsync(string subscriptionId, string resourceGroupName, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateListForResourceGroupRequest(subscriptionId, resourceGroupName, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the list of all policy assignments associated with the given resource group in the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource group, including those that apply directly or apply from containing scopes, as well as any applied to resources contained within the resource group. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource group, which is everything in the unfiltered list except those applied to resources contained within the resource group. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource group. - /// The ID of the target subscription. - /// The name of the resource group that contains policy assignments. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response ListForResourceGroup(string subscriptionId, string resourceGroupName, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateListForResourceGroupRequest(subscriptionId, resourceGroupName, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListForResourceRequestUri(string subscriptionId, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/", false); - uri.AppendPath(parentResourcePath, false); - uri.AppendPath("/", false); - uri.AppendPath(resourceType, false); - uri.AppendPath("/", false); - uri.AppendPath(resourceName, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListForResourceRequest(string subscriptionId, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/", false); - uri.AppendPath(parentResourcePath, false); - uri.AppendPath("/", false); - uri.AppendPath(resourceType, false); - uri.AppendPath("/", false); - uri.AppendPath(resourceName, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the list of all policy assignments associated with the specified resource in the given resource group and subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource, including those that apply directly or from all containing scopes, as well as any applied to resources contained within the resource. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource, which is everything in the unfiltered list except those applied to resources contained within the resource. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource level. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource. Three parameters plus the resource name are used to identify a specific resource. If the resource is not part of a parent resource (the more common case), the parent resource path should not be provided (or provided as ''). For example a web app could be specified as ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', {resourceType} == 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent resource, then all parameters should be provided. For example a virtual machine DNS name could be specified as ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == 'MyComputerName'). A convenient alternative to providing the namespace and type name separately is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == 'MyWebApp'). - /// The ID of the target subscription. - /// The name of the resource group containing the resource. - /// The namespace of the resource provider. For example, the namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). - /// The parent resource path. Use empty string if there is none. - /// The resource type name. For example the type name of a web app is 'sites' (from Microsoft.Web/sites). - /// The name of the resource. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// , , , , or is null. - /// , , or is an empty string, and was expected to be non-empty. - public async Task> ListForResourceAsync(string subscriptionId, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNull(parentResourcePath, nameof(parentResourcePath)); - Argument.AssertNotNull(resourceType, nameof(resourceType)); - Argument.AssertNotNullOrEmpty(resourceName, nameof(resourceName)); - - using var message = CreateListForResourceRequest(subscriptionId, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the list of all policy assignments associated with the specified resource in the given resource group and subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource, including those that apply directly or from all containing scopes, as well as any applied to resources contained within the resource. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource, which is everything in the unfiltered list except those applied to resources contained within the resource. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource level. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource. Three parameters plus the resource name are used to identify a specific resource. If the resource is not part of a parent resource (the more common case), the parent resource path should not be provided (or provided as ''). For example a web app could be specified as ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', {resourceType} == 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent resource, then all parameters should be provided. For example a virtual machine DNS name could be specified as ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == 'MyComputerName'). A convenient alternative to providing the namespace and type name separately is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == 'MyWebApp'). - /// The ID of the target subscription. - /// The name of the resource group containing the resource. - /// The namespace of the resource provider. For example, the namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). - /// The parent resource path. Use empty string if there is none. - /// The resource type name. For example the type name of a web app is 'sites' (from Microsoft.Web/sites). - /// The name of the resource. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// , , , , or is null. - /// , , or is an empty string, and was expected to be non-empty. - public Response ListForResource(string subscriptionId, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNull(parentResourcePath, nameof(parentResourcePath)); - Argument.AssertNotNull(resourceType, nameof(resourceType)); - Argument.AssertNotNullOrEmpty(resourceName, nameof(resourceName)); - - using var message = CreateListForResourceRequest(subscriptionId, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListForManagementGroupRequestUri(string managementGroupId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListForManagementGroupRequest(string managementGroupId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the list of all policy assignments applicable to the management group that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter=atScope() is provided, the returned list includes all policy assignments that are assigned to the management group or the management group's ancestors. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the management group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the management group. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListForManagementGroupAsync(string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListForManagementGroupRequest(managementGroupId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the list of all policy assignments applicable to the management group that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter=atScope() is provided, the returned list includes all policy assignments that are assigned to the management group or the management group's ancestors. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the management group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the management group. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response ListForManagementGroup(string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListForManagementGroupRequest(managementGroupId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri(string subscriptionId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListRequest(string subscriptionId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the list of all policy assignments associated with the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the subscription, including those that apply directly or from management groups that contain the given subscription, as well as any applied to objects contained within the subscription. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the subscription, which is everything in the unfiltered list except those applied to objects contained within the subscription. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the subscription. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListAsync(string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the list of all policy assignments associated with the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the subscription, including those that apply directly or from management groups that contain the given subscription, as well as any applied to objects contained within the subscription. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the subscription, which is everything in the unfiltered list except those applied to objects contained within the subscription. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the subscription. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response List(string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListForResourceGroupNextPageRequestUri(string nextLink, string subscriptionId, string resourceGroupName, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListForResourceGroupNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the list of all policy assignments associated with the given resource group in the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource group, including those that apply directly or apply from containing scopes, as well as any applied to resources contained within the resource group. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource group, which is everything in the unfiltered list except those applied to resources contained within the resource group. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource group. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The name of the resource group that contains policy assignments. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> ListForResourceGroupNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateListForResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the list of all policy assignments associated with the given resource group in the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource group, including those that apply directly or apply from containing scopes, as well as any applied to resources contained within the resource group. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource group, which is everything in the unfiltered list except those applied to resources contained within the resource group. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource group. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The name of the resource group that contains policy assignments. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response ListForResourceGroupNextPage(string nextLink, string subscriptionId, string resourceGroupName, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateListForResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListForResourceNextPageRequestUri(string nextLink, string subscriptionId, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListForResourceNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the list of all policy assignments associated with the specified resource in the given resource group and subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource, including those that apply directly or from all containing scopes, as well as any applied to resources contained within the resource. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource, which is everything in the unfiltered list except those applied to resources contained within the resource. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource level. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource. Three parameters plus the resource name are used to identify a specific resource. If the resource is not part of a parent resource (the more common case), the parent resource path should not be provided (or provided as ''). For example a web app could be specified as ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', {resourceType} == 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent resource, then all parameters should be provided. For example a virtual machine DNS name could be specified as ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == 'MyComputerName'). A convenient alternative to providing the namespace and type name separately is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == 'MyWebApp'). - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The name of the resource group containing the resource. - /// The namespace of the resource provider. For example, the namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). - /// The parent resource path. Use empty string if there is none. - /// The resource type name. For example the type name of a web app is 'sites' (from Microsoft.Web/sites). - /// The name of the resource. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// , , , , , or is null. - /// , , or is an empty string, and was expected to be non-empty. - public async Task> ListForResourceNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNull(parentResourcePath, nameof(parentResourcePath)); - Argument.AssertNotNull(resourceType, nameof(resourceType)); - Argument.AssertNotNullOrEmpty(resourceName, nameof(resourceName)); - - using var message = CreateListForResourceNextPageRequest(nextLink, subscriptionId, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the list of all policy assignments associated with the specified resource in the given resource group and subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource, including those that apply directly or from all containing scopes, as well as any applied to resources contained within the resource. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource, which is everything in the unfiltered list except those applied to resources contained within the resource. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource level. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource. Three parameters plus the resource name are used to identify a specific resource. If the resource is not part of a parent resource (the more common case), the parent resource path should not be provided (or provided as ''). For example a web app could be specified as ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', {resourceType} == 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent resource, then all parameters should be provided. For example a virtual machine DNS name could be specified as ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == 'MyComputerName'). A convenient alternative to providing the namespace and type name separately is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == 'MyWebApp'). - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The name of the resource group containing the resource. - /// The namespace of the resource provider. For example, the namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). - /// The parent resource path. Use empty string if there is none. - /// The resource type name. For example the type name of a web app is 'sites' (from Microsoft.Web/sites). - /// The name of the resource. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// , , , , , or is null. - /// , , or is an empty string, and was expected to be non-empty. - public Response ListForResourceNextPage(string nextLink, string subscriptionId, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNull(parentResourcePath, nameof(parentResourcePath)); - Argument.AssertNotNull(resourceType, nameof(resourceType)); - Argument.AssertNotNullOrEmpty(resourceName, nameof(resourceName)); - - using var message = CreateListForResourceNextPageRequest(nextLink, subscriptionId, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListForManagementGroupNextPageRequestUri(string nextLink, string managementGroupId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListForManagementGroupNextPageRequest(string nextLink, string managementGroupId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the list of all policy assignments applicable to the management group that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter=atScope() is provided, the returned list includes all policy assignments that are assigned to the management group or the management group's ancestors. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the management group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the management group. - /// The URL to the next page of results. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListForManagementGroupNextPageAsync(string nextLink, string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListForManagementGroupNextPageRequest(nextLink, managementGroupId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the list of all policy assignments applicable to the management group that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter=atScope() is provided, the returned list includes all policy assignments that are assigned to the management group or the management group's ancestors. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the management group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the management group. - /// The URL to the next page of results. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListForManagementGroupNextPage(string nextLink, string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListForManagementGroupNextPageRequest(nextLink, managementGroupId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string subscriptionId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the list of all policy assignments associated with the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the subscription, including those that apply directly or from management groups that contain the given subscription, as well as any applied to objects contained within the subscription. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the subscription, which is everything in the unfiltered list except those applied to objects contained within the subscription. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the subscription. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListNextPageAsync(string nextLink, string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the list of all policy assignments associated with the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the subscription, including those that apply directly or from management groups that contain the given subscription, as well as any applied to objects contained within the subscription. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the subscription, which is everything in the unfiltered list except those applied to objects contained within the subscription. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the subscription. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListNextPage(string nextLink, string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicyDefinitionsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicyDefinitionsRestOperations.cs deleted file mode 100644 index d8a8f6ee24..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicyDefinitionsRestOperations.cs +++ /dev/null @@ -1,1145 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class PolicyDefinitionsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of PolicyDefinitionsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public PolicyDefinitionsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2021-06-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateCreateOrUpdateRequestUri(string subscriptionId, string policyDefinitionName, PolicyDefinitionData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string policyDefinitionName, PolicyDefinitionData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// This operation creates or updates a policy definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy definition to create. - /// The policy definition properties. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> CreateOrUpdateAsync(string subscriptionId, string policyDefinitionName, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateRequest(subscriptionId, policyDefinitionName, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 201: - { - PolicyDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation creates or updates a policy definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy definition to create. - /// The policy definition properties. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response CreateOrUpdate(string subscriptionId, string policyDefinitionName, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateRequest(subscriptionId, policyDefinitionName, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 201: - { - PolicyDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteRequestUri(string subscriptionId, string policyDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteRequest(string subscriptionId, string policyDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation deletes the policy definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy definition to delete. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task DeleteAsync(string subscriptionId, string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateDeleteRequest(subscriptionId, policyDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation deletes the policy definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy definition to delete. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Delete(string subscriptionId, string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateDeleteRequest(subscriptionId, policyDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetRequestUri(string subscriptionId, string policyDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetRequest(string subscriptionId, string policyDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the policy definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy definition to get. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> GetAsync(string subscriptionId, string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateGetRequest(subscriptionId, policyDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicyDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the policy definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy definition to get. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Get(string subscriptionId, string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateGetRequest(subscriptionId, policyDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicyDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetBuiltInRequestUri(string policyDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetBuiltInRequest(string policyDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the built-in policy definition with the given name. - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetBuiltInAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateGetBuiltInRequest(policyDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicyDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the built-in policy definition with the given name. - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response GetBuiltIn(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateGetBuiltInRequest(policyDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicyDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateCreateOrUpdateAtManagementGroupRequestUri(string managementGroupId, string policyDefinitionName, PolicyDefinitionData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateAtManagementGroupRequest(string managementGroupId, string policyDefinitionName, PolicyDefinitionData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// This operation creates or updates a policy definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy definition to create. - /// The policy definition properties. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> CreateOrUpdateAtManagementGroupAsync(string managementGroupId, string policyDefinitionName, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateAtManagementGroupRequest(managementGroupId, policyDefinitionName, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 201: - { - PolicyDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation creates or updates a policy definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy definition to create. - /// The policy definition properties. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response CreateOrUpdateAtManagementGroup(string managementGroupId, string policyDefinitionName, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateAtManagementGroupRequest(managementGroupId, policyDefinitionName, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 201: - { - PolicyDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteAtManagementGroupRequestUri(string managementGroupId, string policyDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteAtManagementGroupRequest(string managementGroupId, string policyDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation deletes the policy definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy definition to delete. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task DeleteAtManagementGroupAsync(string managementGroupId, string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateDeleteAtManagementGroupRequest(managementGroupId, policyDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation deletes the policy definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy definition to delete. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response DeleteAtManagementGroup(string managementGroupId, string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateDeleteAtManagementGroupRequest(managementGroupId, policyDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetAtManagementGroupRequestUri(string managementGroupId, string policyDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetAtManagementGroupRequest(string managementGroupId, string policyDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the policy definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy definition to get. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> GetAtManagementGroupAsync(string managementGroupId, string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateGetAtManagementGroupRequest(managementGroupId, policyDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicyDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the policy definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy definition to get. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response GetAtManagementGroup(string managementGroupId, string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateGetAtManagementGroupRequest(managementGroupId, policyDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicyDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri(string subscriptionId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - return uri; - } - - internal HttpMessage CreateListRequest(string subscriptionId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the policy definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListAsync(string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the policy definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response List(string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListBuiltInRequestUri(string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - return uri; - } - - internal HttpMessage CreateListBuiltInRequest(string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the built-in policy definitions that match the optional given $filter. If $filter='policyType -eq {value}' is provided, the returned list only includes all built-in policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy definitions whose category match the {value}. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - public async Task> ListBuiltInAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - using var message = CreateListBuiltInRequest(filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the built-in policy definitions that match the optional given $filter. If $filter='policyType -eq {value}' is provided, the returned list only includes all built-in policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy definitions whose category match the {value}. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - public Response ListBuiltIn(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - using var message = CreateListBuiltInRequest(filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListByManagementGroupRequestUri(string managementGroupId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - return uri; - } - - internal HttpMessage CreateListByManagementGroupRequest(string managementGroupId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the policy definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListByManagementGroupAsync(string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListByManagementGroupRequest(managementGroupId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the policy definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response ListByManagementGroup(string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListByManagementGroupRequest(managementGroupId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string subscriptionId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the policy definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListNextPageAsync(string nextLink, string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the policy definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListNextPage(string nextLink, string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListBuiltInNextPageRequestUri(string nextLink, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListBuiltInNextPageRequest(string nextLink, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the built-in policy definitions that match the optional given $filter. If $filter='policyType -eq {value}' is provided, the returned list only includes all built-in policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy definitions whose category match the {value}. - /// The URL to the next page of results. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - public async Task> ListBuiltInNextPageAsync(string nextLink, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListBuiltInNextPageRequest(nextLink, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the built-in policy definitions that match the optional given $filter. If $filter='policyType -eq {value}' is provided, the returned list only includes all built-in policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy definitions whose category match the {value}. - /// The URL to the next page of results. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - public Response ListBuiltInNextPage(string nextLink, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListBuiltInNextPageRequest(nextLink, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListByManagementGroupNextPageRequestUri(string nextLink, string managementGroupId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListByManagementGroupNextPageRequest(string nextLink, string managementGroupId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the policy definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// The URL to the next page of results. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListByManagementGroupNextPageAsync(string nextLink, string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListByManagementGroupNextPageRequest(nextLink, managementGroupId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the policy definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// The URL to the next page of results. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListByManagementGroupNextPage(string nextLink, string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListByManagementGroupNextPageRequest(nextLink, managementGroupId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicySetDefinitionsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicySetDefinitionsRestOperations.cs deleted file mode 100644 index 74741a5519..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicySetDefinitionsRestOperations.cs +++ /dev/null @@ -1,1149 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class PolicySetDefinitionsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of PolicySetDefinitionsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public PolicySetDefinitionsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2021-06-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateCreateOrUpdateRequestUri(string subscriptionId, string policySetDefinitionName, PolicySetDefinitionData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string policySetDefinitionName, PolicySetDefinitionData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// This operation creates or updates a policy set definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy set definition to create. - /// The policy set definition properties. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> CreateOrUpdateAsync(string subscriptionId, string policySetDefinitionName, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateRequest(subscriptionId, policySetDefinitionName, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 201: - { - PolicySetDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation creates or updates a policy set definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy set definition to create. - /// The policy set definition properties. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response CreateOrUpdate(string subscriptionId, string policySetDefinitionName, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateRequest(subscriptionId, policySetDefinitionName, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 201: - { - PolicySetDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteRequestUri(string subscriptionId, string policySetDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteRequest(string subscriptionId, string policySetDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation deletes the policy set definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy set definition to delete. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task DeleteAsync(string subscriptionId, string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateDeleteRequest(subscriptionId, policySetDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation deletes the policy set definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy set definition to delete. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Delete(string subscriptionId, string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateDeleteRequest(subscriptionId, policySetDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetRequestUri(string subscriptionId, string policySetDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetRequest(string subscriptionId, string policySetDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the policy set definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> GetAsync(string subscriptionId, string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateGetRequest(subscriptionId, policySetDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicySetDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the policy set definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Get(string subscriptionId, string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateGetRequest(subscriptionId, policySetDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicySetDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetBuiltInRequestUri(string policySetDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetBuiltInRequest(string policySetDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the built-in policy set definition with the given name. - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetBuiltInAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateGetBuiltInRequest(policySetDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicySetDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the built-in policy set definition with the given name. - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response GetBuiltIn(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateGetBuiltInRequest(policySetDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicySetDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri(string subscriptionId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - return uri; - } - - internal HttpMessage CreateListRequest(string subscriptionId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the policy set definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListAsync(string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the policy set definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response List(string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListBuiltInRequestUri(string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - return uri; - } - - internal HttpMessage CreateListBuiltInRequest(string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the built-in policy set definitions that match the optional given $filter. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy set definitions whose category match the {value}. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - public async Task> ListBuiltInAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - using var message = CreateListBuiltInRequest(filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the built-in policy set definitions that match the optional given $filter. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy set definitions whose category match the {value}. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - public Response ListBuiltIn(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - using var message = CreateListBuiltInRequest(filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateCreateOrUpdateAtManagementGroupRequestUri(string managementGroupId, string policySetDefinitionName, PolicySetDefinitionData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateAtManagementGroupRequest(string managementGroupId, string policySetDefinitionName, PolicySetDefinitionData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// This operation creates or updates a policy set definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy set definition to create. - /// The policy set definition properties. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> CreateOrUpdateAtManagementGroupAsync(string managementGroupId, string policySetDefinitionName, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateAtManagementGroupRequest(managementGroupId, policySetDefinitionName, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 201: - { - PolicySetDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation creates or updates a policy set definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy set definition to create. - /// The policy set definition properties. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response CreateOrUpdateAtManagementGroup(string managementGroupId, string policySetDefinitionName, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateAtManagementGroupRequest(managementGroupId, policySetDefinitionName, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 201: - { - PolicySetDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteAtManagementGroupRequestUri(string managementGroupId, string policySetDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteAtManagementGroupRequest(string managementGroupId, string policySetDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation deletes the policy set definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy set definition to delete. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task DeleteAtManagementGroupAsync(string managementGroupId, string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateDeleteAtManagementGroupRequest(managementGroupId, policySetDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation deletes the policy set definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy set definition to delete. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response DeleteAtManagementGroup(string managementGroupId, string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateDeleteAtManagementGroupRequest(managementGroupId, policySetDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetAtManagementGroupRequestUri(string managementGroupId, string policySetDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetAtManagementGroupRequest(string managementGroupId, string policySetDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the policy set definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> GetAtManagementGroupAsync(string managementGroupId, string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateGetAtManagementGroupRequest(managementGroupId, policySetDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicySetDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the policy set definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response GetAtManagementGroup(string managementGroupId, string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateGetAtManagementGroupRequest(managementGroupId, policySetDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicySetDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListByManagementGroupRequestUri(string managementGroupId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - return uri; - } - - internal HttpMessage CreateListByManagementGroupRequest(string managementGroupId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the policy set definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListByManagementGroupAsync(string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListByManagementGroupRequest(managementGroupId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the policy set definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response ListByManagementGroup(string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListByManagementGroupRequest(managementGroupId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string subscriptionId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the policy set definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListNextPageAsync(string nextLink, string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the policy set definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListNextPage(string nextLink, string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListBuiltInNextPageRequestUri(string nextLink, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListBuiltInNextPageRequest(string nextLink, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the built-in policy set definitions that match the optional given $filter. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy set definitions whose category match the {value}. - /// The URL to the next page of results. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - public async Task> ListBuiltInNextPageAsync(string nextLink, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListBuiltInNextPageRequest(nextLink, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the built-in policy set definitions that match the optional given $filter. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy set definitions whose category match the {value}. - /// The URL to the next page of results. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - public Response ListBuiltInNextPage(string nextLink, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListBuiltInNextPageRequest(nextLink, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListByManagementGroupNextPageRequestUri(string nextLink, string managementGroupId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListByManagementGroupNextPageRequest(string nextLink, string managementGroupId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the policy set definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// The URL to the next page of results. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListByManagementGroupNextPageAsync(string nextLink, string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListByManagementGroupNextPageRequest(nextLink, managementGroupId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the policy set definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// The URL to the next page of results. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListByManagementGroupNextPage(string nextLink, string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListByManagementGroupNextPageRequest(nextLink, managementGroupId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ProviderResourceTypesRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ProviderResourceTypesRestOperations.cs deleted file mode 100644 index 3acae9da9e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ProviderResourceTypesRestOperations.cs +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class ProviderResourceTypesRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of ProviderResourceTypesRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public ProviderResourceTypesRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2022-09-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateListRequestUri(string subscriptionId, string resourceProviderNamespace, string expand) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/resourceTypes", false); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListRequest(string subscriptionId, string resourceProviderNamespace, string expand) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/resourceTypes", false); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// List the resource types for a specified resource provider. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> ListAsync(string subscriptionId, string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateListRequest(subscriptionId, resourceProviderNamespace, expand); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ProviderResourceTypeListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ProviderResourceTypeListResult.DeserializeProviderResourceTypeListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// List the resource types for a specified resource provider. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response List(string subscriptionId, string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateListRequest(subscriptionId, resourceProviderNamespace, expand); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ProviderResourceTypeListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ProviderResourceTypeListResult.DeserializeProviderResourceTypeListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ProvidersRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ProvidersRestOperations.cs deleted file mode 100644 index 63f444d6e3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ProvidersRestOperations.cs +++ /dev/null @@ -1,802 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class ProvidersRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of ProvidersRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public ProvidersRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2022-09-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateUnregisterRequestUri(string subscriptionId, string resourceProviderNamespace) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/unregister", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateUnregisterRequest(string subscriptionId, string resourceProviderNamespace) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/unregister", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Unregisters a subscription from a resource provider. - /// The ID of the target subscription. - /// The namespace of the resource provider to unregister. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> UnregisterAsync(string subscriptionId, string resourceProviderNamespace, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateUnregisterRequest(subscriptionId, resourceProviderNamespace); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceProviderData.DeserializeResourceProviderData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Unregisters a subscription from a resource provider. - /// The ID of the target subscription. - /// The namespace of the resource provider to unregister. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Unregister(string subscriptionId, string resourceProviderNamespace, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateUnregisterRequest(subscriptionId, resourceProviderNamespace); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceProviderData.DeserializeResourceProviderData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateProviderPermissionsRequestUri(string subscriptionId, string resourceProviderNamespace) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/providerPermissions", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateProviderPermissionsRequest(string subscriptionId, string resourceProviderNamespace) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/providerPermissions", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Get the provider permissions. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> ProviderPermissionsAsync(string subscriptionId, string resourceProviderNamespace, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateProviderPermissionsRequest(subscriptionId, resourceProviderNamespace); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ProviderPermissionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ProviderPermissionListResult.DeserializeProviderPermissionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Get the provider permissions. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response ProviderPermissions(string subscriptionId, string resourceProviderNamespace, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateProviderPermissionsRequest(subscriptionId, resourceProviderNamespace); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ProviderPermissionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ProviderPermissionListResult.DeserializeProviderPermissionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateRegisterRequestUri(string subscriptionId, string resourceProviderNamespace, ProviderRegistrationContent content) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/register", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateRegisterRequest(string subscriptionId, string resourceProviderNamespace, ProviderRegistrationContent content) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/register", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - if (content != null) - { - request.Headers.Add("Content-Type", "application/json"); - var content0 = new Utf8JsonRequestContent(); - content0.JsonWriter.WriteObjectValue(content, ModelSerializationExtensions.WireOptions); - request.Content = content0; - } - _userAgent.Apply(message); - return message; - } - - /// Registers a subscription with a resource provider. - /// The ID of the target subscription. - /// The namespace of the resource provider to register. - /// The third party consent for S2S. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> RegisterAsync(string subscriptionId, string resourceProviderNamespace, ProviderRegistrationContent content = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateRegisterRequest(subscriptionId, resourceProviderNamespace, content); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceProviderData.DeserializeResourceProviderData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Registers a subscription with a resource provider. - /// The ID of the target subscription. - /// The namespace of the resource provider to register. - /// The third party consent for S2S. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Register(string subscriptionId, string resourceProviderNamespace, ProviderRegistrationContent content = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateRegisterRequest(subscriptionId, resourceProviderNamespace, content); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceProviderData.DeserializeResourceProviderData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri(string subscriptionId, string expand) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers", false); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListRequest(string subscriptionId, string expand) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers", false); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all resource providers for a subscription. - /// The ID of the target subscription. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListAsync(string subscriptionId, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, expand); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceProviderListResult.DeserializeResourceProviderListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all resource providers for a subscription. - /// The ID of the target subscription. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response List(string subscriptionId, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, expand); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceProviderListResult.DeserializeResourceProviderListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListAtTenantScopeRequestUri(string expand) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers", false); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListAtTenantScopeRequest(string expand) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers", false); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all resource providers for the tenant. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - public async Task> ListAtTenantScopeAsync(string expand = null, CancellationToken cancellationToken = default) - { - using var message = CreateListAtTenantScopeRequest(expand); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - TenantResourceProviderListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = TenantResourceProviderListResult.DeserializeTenantResourceProviderListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all resource providers for the tenant. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - public Response ListAtTenantScope(string expand = null, CancellationToken cancellationToken = default) - { - using var message = CreateListAtTenantScopeRequest(expand); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - TenantResourceProviderListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = TenantResourceProviderListResult.DeserializeTenantResourceProviderListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetRequestUri(string subscriptionId, string resourceProviderNamespace, string expand) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetRequest(string subscriptionId, string resourceProviderNamespace, string expand) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets the specified resource provider. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> GetAsync(string subscriptionId, string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateGetRequest(subscriptionId, resourceProviderNamespace, expand); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceProviderData.DeserializeResourceProviderData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ResourceProviderData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets the specified resource provider. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Get(string subscriptionId, string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateGetRequest(subscriptionId, resourceProviderNamespace, expand); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceProviderData.DeserializeResourceProviderData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ResourceProviderData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetAtTenantScopeRequestUri(string resourceProviderNamespace, string expand) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetAtTenantScopeRequest(string resourceProviderNamespace, string expand) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets the specified resource provider at the tenant level. - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetAtTenantScopeAsync(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateGetAtTenantScopeRequest(resourceProviderNamespace, expand); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - TenantResourceProvider value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = TenantResourceProvider.DeserializeTenantResourceProvider(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets the specified resource provider at the tenant level. - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response GetAtTenantScope(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateGetAtTenantScopeRequest(resourceProviderNamespace, expand); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - TenantResourceProvider value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = TenantResourceProvider.DeserializeTenantResourceProvider(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string subscriptionId, string expand) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string expand) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all resource providers for a subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListNextPageAsync(string nextLink, string subscriptionId, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, expand); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceProviderListResult.DeserializeResourceProviderListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all resource providers for a subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListNextPage(string nextLink, string subscriptionId, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, expand); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceProviderListResult.DeserializeResourceProviderListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListAtTenantScopeNextPageRequestUri(string nextLink, string expand) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListAtTenantScopeNextPageRequest(string nextLink, string expand) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all resource providers for the tenant. - /// The URL to the next page of results. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - public async Task> ListAtTenantScopeNextPageAsync(string nextLink, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListAtTenantScopeNextPageRequest(nextLink, expand); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - TenantResourceProviderListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = TenantResourceProviderListResult.DeserializeTenantResourceProviderListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all resource providers for the tenant. - /// The URL to the next page of results. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - public Response ListAtTenantScopeNextPage(string nextLink, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListAtTenantScopeNextPageRequest(nextLink, expand); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - TenantResourceProviderListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = TenantResourceProviderListResult.DeserializeTenantResourceProviderListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourceGroupsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourceGroupsRestOperations.cs deleted file mode 100644 index 06b9758562..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourceGroupsRestOperations.cs +++ /dev/null @@ -1,663 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class ResourceGroupsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of ResourceGroupsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public ResourceGroupsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2022-09-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateCreateOrUpdateRequestUri(string subscriptionId, string resourceGroupName, ResourceGroupData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, ResourceGroupData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// Creates or updates a resource group. - /// The ID of the target subscription. - /// The name of the resource group to create or update. Can include alphanumeric, underscore, parentheses, hyphen, period (except at end), and Unicode characters that match the allowed characters. - /// Parameters supplied to the create or update a resource group. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> CreateOrUpdateAsync(string subscriptionId, string resourceGroupName, ResourceGroupData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 201: - { - ResourceGroupData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceGroupData.DeserializeResourceGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Creates or updates a resource group. - /// The ID of the target subscription. - /// The name of the resource group to create or update. Can include alphanumeric, underscore, parentheses, hyphen, period (except at end), and Unicode characters that match the allowed characters. - /// Parameters supplied to the create or update a resource group. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response CreateOrUpdate(string subscriptionId, string resourceGroupName, ResourceGroupData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 201: - { - ResourceGroupData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceGroupData.DeserializeResourceGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteRequestUri(string subscriptionId, string resourceGroupName, string forceDeletionTypes) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - if (forceDeletionTypes != null) - { - uri.AppendQuery("forceDeletionTypes", forceDeletionTypes, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string forceDeletionTypes) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - if (forceDeletionTypes != null) - { - uri.AppendQuery("forceDeletionTypes", forceDeletionTypes, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// When you delete a resource group, all of its resources are also deleted. Deleting a resource group deletes all of its template deployments and currently stored operations. - /// The ID of the target subscription. - /// The name of the resource group to delete. The name is case insensitive. - /// The resource types you want to force delete. Currently, only the following is supported: forceDeletionTypes=Microsoft.Compute/virtualMachines,Microsoft.Compute/virtualMachineScaleSets. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task DeleteAsync(string subscriptionId, string resourceGroupName, string forceDeletionTypes = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, forceDeletionTypes); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// When you delete a resource group, all of its resources are also deleted. Deleting a resource group deletes all of its template deployments and currently stored operations. - /// The ID of the target subscription. - /// The name of the resource group to delete. The name is case insensitive. - /// The resource types you want to force delete. Currently, only the following is supported: forceDeletionTypes=Microsoft.Compute/virtualMachines,Microsoft.Compute/virtualMachineScaleSets. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Delete(string subscriptionId, string resourceGroupName, string forceDeletionTypes = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, forceDeletionTypes); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetRequestUri(string subscriptionId, string resourceGroupName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets a resource group. - /// The ID of the target subscription. - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> GetAsync(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateGetRequest(subscriptionId, resourceGroupName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceGroupData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceGroupData.DeserializeResourceGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ResourceGroupData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets a resource group. - /// The ID of the target subscription. - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Get(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateGetRequest(subscriptionId, resourceGroupName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceGroupData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceGroupData.DeserializeResourceGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ResourceGroupData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateUpdateRequestUri(string subscriptionId, string resourceGroupName, ResourceGroupPatch patch) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateUpdateRequest(string subscriptionId, string resourceGroupName, ResourceGroupPatch patch) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Patch; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(patch, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// Resource groups can be updated through a simple PATCH operation to a group address. The format of the request is the same as that for creating a resource group. If a field is unspecified, the current value is retained. - /// The ID of the target subscription. - /// The name of the resource group to update. The name is case insensitive. - /// Parameters supplied to update a resource group. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> UpdateAsync(string subscriptionId, string resourceGroupName, ResourceGroupPatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNull(patch, nameof(patch)); - - using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, patch); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceGroupData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceGroupData.DeserializeResourceGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Resource groups can be updated through a simple PATCH operation to a group address. The format of the request is the same as that for creating a resource group. If a field is unspecified, the current value is retained. - /// The ID of the target subscription. - /// The name of the resource group to update. The name is case insensitive. - /// Parameters supplied to update a resource group. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Update(string subscriptionId, string resourceGroupName, ResourceGroupPatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNull(patch, nameof(patch)); - - using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, patch); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceGroupData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceGroupData.DeserializeResourceGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateExportTemplateRequestUri(string subscriptionId, string resourceGroupName, ExportTemplate exportTemplate) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendPath("/exportTemplate", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateExportTemplateRequest(string subscriptionId, string resourceGroupName, ExportTemplate exportTemplate) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendPath("/exportTemplate", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(exportTemplate, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// Captures the specified resource group as a template. - /// The ID of the target subscription. - /// The name of the resource group. The name is case insensitive. - /// Parameters for exporting the template. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task ExportTemplateAsync(string subscriptionId, string resourceGroupName, ExportTemplate exportTemplate, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNull(exportTemplate, nameof(exportTemplate)); - - using var message = CreateExportTemplateRequest(subscriptionId, resourceGroupName, exportTemplate); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// Captures the specified resource group as a template. - /// The ID of the target subscription. - /// The name of the resource group. The name is case insensitive. - /// Parameters for exporting the template. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response ExportTemplate(string subscriptionId, string resourceGroupName, ExportTemplate exportTemplate, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNull(exportTemplate, nameof(exportTemplate)); - - using var message = CreateExportTemplateRequest(subscriptionId, resourceGroupName, exportTemplate); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri(string subscriptionId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListRequest(string subscriptionId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all the resource groups for a subscription. - /// The ID of the target subscription. - /// The filter to apply on the operation.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. - /// The number of results to return. If null is passed, returns all resource groups. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListAsync(string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceGroupListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceGroupListResult.DeserializeResourceGroupListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all the resource groups for a subscription. - /// The ID of the target subscription. - /// The filter to apply on the operation.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. - /// The number of results to return. If null is passed, returns all resource groups. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response List(string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceGroupListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceGroupListResult.DeserializeResourceGroupListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string subscriptionId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all the resource groups for a subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. - /// The number of results to return. If null is passed, returns all resource groups. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListNextPageAsync(string nextLink, string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceGroupListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceGroupListResult.DeserializeResourceGroupListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all the resource groups for a subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. - /// The number of results to return. If null is passed, returns all resource groups. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListNextPage(string nextLink, string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceGroupListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceGroupListResult.DeserializeResourceGroupListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourceManagementRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourceManagementRestOperations.cs deleted file mode 100644 index 490f691f55..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourceManagementRestOperations.cs +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class ResourceManagementRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of ResourceManagementRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public ResourceManagementRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2022-12-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateCheckResourceNameRequestUri(ResourceNameValidationContent content) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Resources/checkResourceName", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCheckResourceNameRequest(ResourceNameValidationContent content) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Resources/checkResourceName", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - if (content != null) - { - request.Headers.Add("Content-Type", "application/json"); - var content0 = new Utf8JsonRequestContent(); - content0.JsonWriter.WriteObjectValue(content, ModelSerializationExtensions.WireOptions); - request.Content = content0; - } - _userAgent.Apply(message); - return message; - } - - /// A resource name is valid if it is not a reserved word, does not contains a reserved word and does not start with a reserved word. - /// Resource object with values for resource name and resource type. - /// The cancellation token to use. - public async Task> CheckResourceNameAsync(ResourceNameValidationContent content = null, CancellationToken cancellationToken = default) - { - using var message = CreateCheckResourceNameRequest(content); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceNameValidationResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceNameValidationResult.DeserializeResourceNameValidationResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// A resource name is valid if it is not a reserved word, does not contains a reserved word and does not start with a reserved word. - /// Resource object with values for resource name and resource type. - /// The cancellation token to use. - public Response CheckResourceName(ResourceNameValidationContent content = null, CancellationToken cancellationToken = default) - { - using var message = CreateCheckResourceNameRequest(content); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceNameValidationResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceNameValidationResult.DeserializeResourceNameValidationResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourcesRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourcesRestOperations.cs deleted file mode 100644 index c990c23b40..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourcesRestOperations.cs +++ /dev/null @@ -1,915 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class ResourcesRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of ResourcesRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public ResourcesRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2022-09-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateListByResourceGroupRequestUri(string subscriptionId, string resourceGroupName, string filter, string expand, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendPath("/resources", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListByResourceGroupRequest(string subscriptionId, string resourceGroupName, string filter, string expand, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendPath("/resources", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Get all the resources for a resource group. - /// The ID of the target subscription. - /// The resource group with the resources to get. - /// The filter to apply on the operation.<br><br>The properties you can use for eq (equals) or ne (not equals) are: location, resourceType, name, resourceGroup, identity, identity/principalId, plan, plan/publisher, plan/product, plan/name, plan/version, and plan/promotionCode.<br><br>For example, to filter by a resource type, use: $filter=resourceType eq 'Microsoft.Network/virtualNetworks'<br><br>You can use substringof(value, property) in the filter. The properties you can use for substring are: name and resourceGroup.<br><br>For example, to get all resources with 'demo' anywhere in the name, use: $filter=substringof('demo', name)<br><br>You can link more than one substringof together by adding and/or operators.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. When you filter by a tag name and value, the tags for each resource are not returned in the results.<br><br>You can use some properties together when filtering. The combinations you can use are: substringof and/or resourceType, plan and plan/publisher and plan/name, identity and identity/principalId. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of results to return. If null is passed, returns all resources. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> ListByResourceGroupAsync(string subscriptionId, string resourceGroupName, string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName, filter, expand, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceListResult.DeserializeResourceListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Get all the resources for a resource group. - /// The ID of the target subscription. - /// The resource group with the resources to get. - /// The filter to apply on the operation.<br><br>The properties you can use for eq (equals) or ne (not equals) are: location, resourceType, name, resourceGroup, identity, identity/principalId, plan, plan/publisher, plan/product, plan/name, plan/version, and plan/promotionCode.<br><br>For example, to filter by a resource type, use: $filter=resourceType eq 'Microsoft.Network/virtualNetworks'<br><br>You can use substringof(value, property) in the filter. The properties you can use for substring are: name and resourceGroup.<br><br>For example, to get all resources with 'demo' anywhere in the name, use: $filter=substringof('demo', name)<br><br>You can link more than one substringof together by adding and/or operators.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. When you filter by a tag name and value, the tags for each resource are not returned in the results.<br><br>You can use some properties together when filtering. The combinations you can use are: substringof and/or resourceType, plan and plan/publisher and plan/name, identity and identity/principalId. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of results to return. If null is passed, returns all resources. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response ListByResourceGroup(string subscriptionId, string resourceGroupName, string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName, filter, expand, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceListResult.DeserializeResourceListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateMoveResourcesRequestUri(string subscriptionId, string sourceResourceGroupName, ResourcesMoveContent content) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(sourceResourceGroupName, true); - uri.AppendPath("/moveResources", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateMoveResourcesRequest(string subscriptionId, string sourceResourceGroupName, ResourcesMoveContent content) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(sourceResourceGroupName, true); - uri.AppendPath("/moveResources", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content0 = new Utf8JsonRequestContent(); - content0.JsonWriter.WriteObjectValue(content, ModelSerializationExtensions.WireOptions); - request.Content = content0; - _userAgent.Apply(message); - return message; - } - - /// The resources to be moved must be in the same source resource group in the source subscription being used. The target resource group may be in a different subscription. When moving resources, both the source group and the target group are locked for the duration of the operation. Write and delete operations are blocked on the groups until the move completes. - /// The ID of the target subscription. - /// The name of the resource group from the source subscription containing the resources to be moved. - /// Parameters for moving resources. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task MoveResourcesAsync(string subscriptionId, string sourceResourceGroupName, ResourcesMoveContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(sourceResourceGroupName, nameof(sourceResourceGroupName)); - Argument.AssertNotNull(content, nameof(content)); - - using var message = CreateMoveResourcesRequest(subscriptionId, sourceResourceGroupName, content); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 202: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// The resources to be moved must be in the same source resource group in the source subscription being used. The target resource group may be in a different subscription. When moving resources, both the source group and the target group are locked for the duration of the operation. Write and delete operations are blocked on the groups until the move completes. - /// The ID of the target subscription. - /// The name of the resource group from the source subscription containing the resources to be moved. - /// Parameters for moving resources. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response MoveResources(string subscriptionId, string sourceResourceGroupName, ResourcesMoveContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(sourceResourceGroupName, nameof(sourceResourceGroupName)); - Argument.AssertNotNull(content, nameof(content)); - - using var message = CreateMoveResourcesRequest(subscriptionId, sourceResourceGroupName, content); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 202: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateValidateMoveResourcesRequestUri(string subscriptionId, string sourceResourceGroupName, ResourcesMoveContent content) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(sourceResourceGroupName, true); - uri.AppendPath("/validateMoveResources", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateValidateMoveResourcesRequest(string subscriptionId, string sourceResourceGroupName, ResourcesMoveContent content) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(sourceResourceGroupName, true); - uri.AppendPath("/validateMoveResources", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content0 = new Utf8JsonRequestContent(); - content0.JsonWriter.WriteObjectValue(content, ModelSerializationExtensions.WireOptions); - request.Content = content0; - _userAgent.Apply(message); - return message; - } - - /// This operation checks whether the specified resources can be moved to the target. The resources to be moved must be in the same source resource group in the source subscription being used. The target resource group may be in a different subscription. If validation succeeds, it returns HTTP response code 204 (no content). If validation fails, it returns HTTP response code 409 (Conflict) with an error message. Retrieve the URL in the Location header value to check the result of the long-running operation. - /// The ID of the target subscription. - /// The name of the resource group from the source subscription containing the resources to be validated for move. - /// Parameters for moving resources. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task ValidateMoveResourcesAsync(string subscriptionId, string sourceResourceGroupName, ResourcesMoveContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(sourceResourceGroupName, nameof(sourceResourceGroupName)); - Argument.AssertNotNull(content, nameof(content)); - - using var message = CreateValidateMoveResourcesRequest(subscriptionId, sourceResourceGroupName, content); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 202: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation checks whether the specified resources can be moved to the target. The resources to be moved must be in the same source resource group in the source subscription being used. The target resource group may be in a different subscription. If validation succeeds, it returns HTTP response code 204 (no content). If validation fails, it returns HTTP response code 409 (Conflict) with an error message. Retrieve the URL in the Location header value to check the result of the long-running operation. - /// The ID of the target subscription. - /// The name of the resource group from the source subscription containing the resources to be validated for move. - /// Parameters for moving resources. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response ValidateMoveResources(string subscriptionId, string sourceResourceGroupName, ResourcesMoveContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(sourceResourceGroupName, nameof(sourceResourceGroupName)); - Argument.AssertNotNull(content, nameof(content)); - - using var message = CreateValidateMoveResourcesRequest(subscriptionId, sourceResourceGroupName, content); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 202: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri(string subscriptionId, string filter, string expand, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resources", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListRequest(string subscriptionId, string filter, string expand, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resources", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Get all the resources in a subscription. - /// The ID of the target subscription. - /// The filter to apply on the operation.<br><br>Filter comparison operators include `eq` (equals) and `ne` (not equals) and may be used with the following properties: `location`, `resourceType`, `name`, `resourceGroup`, `identity`, `identity/principalId`, `plan`, `plan/publisher`, `plan/product`, `plan/name`, `plan/version`, and `plan/promotionCode`.<br><br>For example, to filter by a resource type, use `$filter=resourceType eq 'Microsoft.Network/virtualNetworks'`<br><br><br>`substringof(value, property)` can be used to filter for substrings of the following currently-supported properties: `name` and `resourceGroup`<br><br>For example, to get all resources with 'demo' anywhere in the resource name, use `$filter=substringof('demo', name)`<br><br>Multiple substring operations can also be combined using `and`/`or` operators.<br><br>Note that any truncated number of results queried via `$top` may also not be compatible when using a filter.<br><br><br>Resources can be filtered by tag names and values. For example, to filter for a tag name and value, use `$filter=tagName eq 'tag1' and tagValue eq 'Value1'`. Note that when resources are filtered by tag name and value, <b>the original tags for each resource will not be returned in the results.</b> Any list of additional properties queried via `$expand` may also not be compatible when filtering by tag names/values. <br><br>For tag names only, resources can be filtered by prefix using the following syntax: `$filter=startswith(tagName, 'depart')`. This query will return all resources with a tag name prefixed by the phrase `depart` (i.e.`department`, `departureDate`, `departureTime`, etc.)<br><br><br>Note that some properties can be combined when filtering resources, which include the following: `substringof() and/or resourceType`, `plan and plan/publisher and plan/name`, and `identity and identity/principalId`. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of recommendations per page if a paged version of this API is being used. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListAsync(string subscriptionId, string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, expand, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceListResult.DeserializeResourceListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Get all the resources in a subscription. - /// The ID of the target subscription. - /// The filter to apply on the operation.<br><br>Filter comparison operators include `eq` (equals) and `ne` (not equals) and may be used with the following properties: `location`, `resourceType`, `name`, `resourceGroup`, `identity`, `identity/principalId`, `plan`, `plan/publisher`, `plan/product`, `plan/name`, `plan/version`, and `plan/promotionCode`.<br><br>For example, to filter by a resource type, use `$filter=resourceType eq 'Microsoft.Network/virtualNetworks'`<br><br><br>`substringof(value, property)` can be used to filter for substrings of the following currently-supported properties: `name` and `resourceGroup`<br><br>For example, to get all resources with 'demo' anywhere in the resource name, use `$filter=substringof('demo', name)`<br><br>Multiple substring operations can also be combined using `and`/`or` operators.<br><br>Note that any truncated number of results queried via `$top` may also not be compatible when using a filter.<br><br><br>Resources can be filtered by tag names and values. For example, to filter for a tag name and value, use `$filter=tagName eq 'tag1' and tagValue eq 'Value1'`. Note that when resources are filtered by tag name and value, <b>the original tags for each resource will not be returned in the results.</b> Any list of additional properties queried via `$expand` may also not be compatible when filtering by tag names/values. <br><br>For tag names only, resources can be filtered by prefix using the following syntax: `$filter=startswith(tagName, 'depart')`. This query will return all resources with a tag name prefixed by the phrase `depart` (i.e.`department`, `departureDate`, `departureTime`, etc.)<br><br><br>Note that some properties can be combined when filtering resources, which include the following: `substringof() and/or resourceType`, `plan and plan/publisher and plan/name`, and `identity and identity/principalId`. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of recommendations per page if a paged version of this API is being used. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response List(string subscriptionId, string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, expand, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceListResult.DeserializeResourceListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteByIdRequestUri(string resourceId, string apiVersion) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(resourceId, false); - uri.AppendQuery("api-version", apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteByIdRequest(string resourceId, string apiVersion) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(resourceId, false); - uri.AppendQuery("api-version", apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Deletes a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The API version to use for the operation. - /// The cancellation token to use. - /// or is null. - public async Task DeleteByIdAsync(string resourceId, string apiVersion, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(resourceId, nameof(resourceId)); - Argument.AssertNotNull(apiVersion, nameof(apiVersion)); - - using var message = CreateDeleteByIdRequest(resourceId, apiVersion); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 202: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// Deletes a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The API version to use for the operation. - /// The cancellation token to use. - /// or is null. - public Response DeleteById(string resourceId, string apiVersion, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(resourceId, nameof(resourceId)); - Argument.AssertNotNull(apiVersion, nameof(apiVersion)); - - using var message = CreateDeleteByIdRequest(resourceId, apiVersion); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 202: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateCreateOrUpdateByIdRequestUri(string resourceId, string apiVersion, GenericResourceData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(resourceId, false); - uri.AppendQuery("api-version", apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateByIdRequest(string resourceId, string apiVersion, GenericResourceData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(resourceId, false); - uri.AppendQuery("api-version", apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// Create a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The API version to use for the operation. - /// Create or update resource parameters. - /// The cancellation token to use. - /// , or is null. - public async Task CreateOrUpdateByIdAsync(string resourceId, string apiVersion, GenericResourceData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(resourceId, nameof(resourceId)); - Argument.AssertNotNull(apiVersion, nameof(apiVersion)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateByIdRequest(resourceId, apiVersion, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 201: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// Create a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The API version to use for the operation. - /// Create or update resource parameters. - /// The cancellation token to use. - /// , or is null. - public Response CreateOrUpdateById(string resourceId, string apiVersion, GenericResourceData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(resourceId, nameof(resourceId)); - Argument.AssertNotNull(apiVersion, nameof(apiVersion)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateByIdRequest(resourceId, apiVersion, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 201: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateUpdateByIdRequestUri(string resourceId, string apiVersion, GenericResourceData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(resourceId, false); - uri.AppendQuery("api-version", apiVersion, true); - return uri; - } - - internal HttpMessage CreateUpdateByIdRequest(string resourceId, string apiVersion, GenericResourceData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Patch; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(resourceId, false); - uri.AppendQuery("api-version", apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// Updates a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The API version to use for the operation. - /// Update resource parameters. - /// The cancellation token to use. - /// , or is null. - public async Task UpdateByIdAsync(string resourceId, string apiVersion, GenericResourceData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(resourceId, nameof(resourceId)); - Argument.AssertNotNull(apiVersion, nameof(apiVersion)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateUpdateByIdRequest(resourceId, apiVersion, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// Updates a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The API version to use for the operation. - /// Update resource parameters. - /// The cancellation token to use. - /// , or is null. - public Response UpdateById(string resourceId, string apiVersion, GenericResourceData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(resourceId, nameof(resourceId)); - Argument.AssertNotNull(apiVersion, nameof(apiVersion)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateUpdateByIdRequest(resourceId, apiVersion, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetByIdRequestUri(string resourceId, string apiVersion) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(resourceId, false); - uri.AppendQuery("api-version", apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetByIdRequest(string resourceId, string apiVersion) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(resourceId, false); - uri.AppendQuery("api-version", apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The API version to use for the operation. - /// The cancellation token to use. - /// or is null. - public async Task> GetByIdAsync(string resourceId, string apiVersion, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(resourceId, nameof(resourceId)); - Argument.AssertNotNull(apiVersion, nameof(apiVersion)); - - using var message = CreateGetByIdRequest(resourceId, apiVersion); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - GenericResourceData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = GenericResourceData.DeserializeGenericResourceData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((GenericResourceData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The API version to use for the operation. - /// The cancellation token to use. - /// or is null. - public Response GetById(string resourceId, string apiVersion, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(resourceId, nameof(resourceId)); - Argument.AssertNotNull(apiVersion, nameof(apiVersion)); - - using var message = CreateGetByIdRequest(resourceId, apiVersion); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - GenericResourceData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = GenericResourceData.DeserializeGenericResourceData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((GenericResourceData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListByResourceGroupNextPageRequestUri(string nextLink, string subscriptionId, string resourceGroupName, string filter, string expand, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListByResourceGroupNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string filter, string expand, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Get all the resources for a resource group. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The resource group with the resources to get. - /// The filter to apply on the operation.<br><br>The properties you can use for eq (equals) or ne (not equals) are: location, resourceType, name, resourceGroup, identity, identity/principalId, plan, plan/publisher, plan/product, plan/name, plan/version, and plan/promotionCode.<br><br>For example, to filter by a resource type, use: $filter=resourceType eq 'Microsoft.Network/virtualNetworks'<br><br>You can use substringof(value, property) in the filter. The properties you can use for substring are: name and resourceGroup.<br><br>For example, to get all resources with 'demo' anywhere in the name, use: $filter=substringof('demo', name)<br><br>You can link more than one substringof together by adding and/or operators.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. When you filter by a tag name and value, the tags for each resource are not returned in the results.<br><br>You can use some properties together when filtering. The combinations you can use are: substringof and/or resourceType, plan and plan/publisher and plan/name, identity and identity/principalId. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of results to return. If null is passed, returns all resources. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> ListByResourceGroupNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName, filter, expand, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceListResult.DeserializeResourceListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Get all the resources for a resource group. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The resource group with the resources to get. - /// The filter to apply on the operation.<br><br>The properties you can use for eq (equals) or ne (not equals) are: location, resourceType, name, resourceGroup, identity, identity/principalId, plan, plan/publisher, plan/product, plan/name, plan/version, and plan/promotionCode.<br><br>For example, to filter by a resource type, use: $filter=resourceType eq 'Microsoft.Network/virtualNetworks'<br><br>You can use substringof(value, property) in the filter. The properties you can use for substring are: name and resourceGroup.<br><br>For example, to get all resources with 'demo' anywhere in the name, use: $filter=substringof('demo', name)<br><br>You can link more than one substringof together by adding and/or operators.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. When you filter by a tag name and value, the tags for each resource are not returned in the results.<br><br>You can use some properties together when filtering. The combinations you can use are: substringof and/or resourceType, plan and plan/publisher and plan/name, identity and identity/principalId. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of results to return. If null is passed, returns all resources. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response ListByResourceGroupNextPage(string nextLink, string subscriptionId, string resourceGroupName, string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName, filter, expand, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceListResult.DeserializeResourceListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string subscriptionId, string filter, string expand, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string filter, string expand, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Get all the resources in a subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation.<br><br>Filter comparison operators include `eq` (equals) and `ne` (not equals) and may be used with the following properties: `location`, `resourceType`, `name`, `resourceGroup`, `identity`, `identity/principalId`, `plan`, `plan/publisher`, `plan/product`, `plan/name`, `plan/version`, and `plan/promotionCode`.<br><br>For example, to filter by a resource type, use `$filter=resourceType eq 'Microsoft.Network/virtualNetworks'`<br><br><br>`substringof(value, property)` can be used to filter for substrings of the following currently-supported properties: `name` and `resourceGroup`<br><br>For example, to get all resources with 'demo' anywhere in the resource name, use `$filter=substringof('demo', name)`<br><br>Multiple substring operations can also be combined using `and`/`or` operators.<br><br>Note that any truncated number of results queried via `$top` may also not be compatible when using a filter.<br><br><br>Resources can be filtered by tag names and values. For example, to filter for a tag name and value, use `$filter=tagName eq 'tag1' and tagValue eq 'Value1'`. Note that when resources are filtered by tag name and value, <b>the original tags for each resource will not be returned in the results.</b> Any list of additional properties queried via `$expand` may also not be compatible when filtering by tag names/values. <br><br>For tag names only, resources can be filtered by prefix using the following syntax: `$filter=startswith(tagName, 'depart')`. This query will return all resources with a tag name prefixed by the phrase `depart` (i.e.`department`, `departureDate`, `departureTime`, etc.)<br><br><br>Note that some properties can be combined when filtering resources, which include the following: `substringof() and/or resourceType`, `plan and plan/publisher and plan/name`, and `identity and identity/principalId`. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of recommendations per page if a paged version of this API is being used. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListNextPageAsync(string nextLink, string subscriptionId, string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, expand, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceListResult.DeserializeResourceListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Get all the resources in a subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation.<br><br>Filter comparison operators include `eq` (equals) and `ne` (not equals) and may be used with the following properties: `location`, `resourceType`, `name`, `resourceGroup`, `identity`, `identity/principalId`, `plan`, `plan/publisher`, `plan/product`, `plan/name`, `plan/version`, and `plan/promotionCode`.<br><br>For example, to filter by a resource type, use `$filter=resourceType eq 'Microsoft.Network/virtualNetworks'`<br><br><br>`substringof(value, property)` can be used to filter for substrings of the following currently-supported properties: `name` and `resourceGroup`<br><br>For example, to get all resources with 'demo' anywhere in the resource name, use `$filter=substringof('demo', name)`<br><br>Multiple substring operations can also be combined using `and`/`or` operators.<br><br>Note that any truncated number of results queried via `$top` may also not be compatible when using a filter.<br><br><br>Resources can be filtered by tag names and values. For example, to filter for a tag name and value, use `$filter=tagName eq 'tag1' and tagValue eq 'Value1'`. Note that when resources are filtered by tag name and value, <b>the original tags for each resource will not be returned in the results.</b> Any list of additional properties queried via `$expand` may also not be compatible when filtering by tag names/values. <br><br>For tag names only, resources can be filtered by prefix using the following syntax: `$filter=startswith(tagName, 'depart')`. This query will return all resources with a tag name prefixed by the phrase `depart` (i.e.`department`, `departureDate`, `departureTime`, etc.)<br><br><br>Note that some properties can be combined when filtering resources, which include the following: `substringof() and/or resourceType`, `plan and plan/publisher and plan/name`, and `identity and identity/principalId`. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of recommendations per page if a paged version of this API is being used. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListNextPage(string nextLink, string subscriptionId, string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, expand, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceListResult.DeserializeResourceListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/SubscriptionsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/SubscriptionsRestOperations.cs deleted file mode 100644 index a5f94cca14..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/SubscriptionsRestOperations.cs +++ /dev/null @@ -1,341 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class SubscriptionsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of SubscriptionsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public SubscriptionsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2022-12-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateListLocationsRequestUri(string subscriptionId, bool? includeExtendedLocations) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/locations", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (includeExtendedLocations != null) - { - uri.AppendQuery("includeExtendedLocations", includeExtendedLocations.Value, true); - } - return uri; - } - - internal HttpMessage CreateListLocationsRequest(string subscriptionId, bool? includeExtendedLocations) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/locations", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (includeExtendedLocations != null) - { - uri.AppendQuery("includeExtendedLocations", includeExtendedLocations.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation provides all the locations that are available for resource providers; however, each resource provider may support a subset of this list. - /// The ID of the target subscription. - /// Whether to include extended locations. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListLocationsAsync(string subscriptionId, bool? includeExtendedLocations = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListLocationsRequest(subscriptionId, includeExtendedLocations); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - LocationListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = LocationListResult.DeserializeLocationListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation provides all the locations that are available for resource providers; however, each resource provider may support a subset of this list. - /// The ID of the target subscription. - /// Whether to include extended locations. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response ListLocations(string subscriptionId, bool? includeExtendedLocations = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListLocationsRequest(subscriptionId, includeExtendedLocations); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - LocationListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = LocationListResult.DeserializeLocationListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetRequestUri(string subscriptionId) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetRequest(string subscriptionId) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets details about a specified subscription. - /// The ID of the target subscription. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetAsync(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateGetRequest(subscriptionId); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - SubscriptionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = SubscriptionData.DeserializeSubscriptionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((SubscriptionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets details about a specified subscription. - /// The ID of the target subscription. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response Get(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateGetRequest(subscriptionId); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - SubscriptionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = SubscriptionData.DeserializeSubscriptionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((SubscriptionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri() - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListRequest() - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all subscriptions for a tenant. - /// The cancellation token to use. - public async Task> ListAsync(CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - SubscriptionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = SubscriptionListResult.DeserializeSubscriptionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all subscriptions for a tenant. - /// The cancellation token to use. - public Response List(CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - SubscriptionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = SubscriptionListResult.DeserializeSubscriptionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all subscriptions for a tenant. - /// The URL to the next page of results. - /// The cancellation token to use. - /// is null. - public async Task> ListNextPageAsync(string nextLink, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - SubscriptionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = SubscriptionListResult.DeserializeSubscriptionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all subscriptions for a tenant. - /// The URL to the next page of results. - /// The cancellation token to use. - /// is null. - public Response ListNextPage(string nextLink, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - SubscriptionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = SubscriptionListResult.DeserializeSubscriptionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/TagsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/TagsRestOperations.cs deleted file mode 100644 index ac7c58fb5a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/TagsRestOperations.cs +++ /dev/null @@ -1,833 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class TagsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of TagsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public TagsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2022-09-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateDeleteValueRequestUri(string subscriptionId, string tagName, string tagValue) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames/", false); - uri.AppendPath(tagName, true); - uri.AppendPath("/tagValues/", false); - uri.AppendPath(tagValue, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteValueRequest(string subscriptionId, string tagName, string tagValue) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames/", false); - uri.AppendPath(tagName, true); - uri.AppendPath("/tagValues/", false); - uri.AppendPath(tagValue, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation allows deleting a value from the list of predefined values for an existing predefined tag name. The value being deleted must not be in use as a tag value for the given tag name for any resource. - /// The ID of the target subscription. - /// The name of the tag. - /// The value of the tag to delete. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public async Task DeleteValueAsync(string subscriptionId, string tagName, string tagValue, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - Argument.AssertNotNullOrEmpty(tagValue, nameof(tagValue)); - - using var message = CreateDeleteValueRequest(subscriptionId, tagName, tagValue); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation allows deleting a value from the list of predefined values for an existing predefined tag name. The value being deleted must not be in use as a tag value for the given tag name for any resource. - /// The ID of the target subscription. - /// The name of the tag. - /// The value of the tag to delete. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public Response DeleteValue(string subscriptionId, string tagName, string tagValue, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - Argument.AssertNotNullOrEmpty(tagValue, nameof(tagValue)); - - using var message = CreateDeleteValueRequest(subscriptionId, tagName, tagValue); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateCreateOrUpdateValueRequestUri(string subscriptionId, string tagName, string tagValue) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames/", false); - uri.AppendPath(tagName, true); - uri.AppendPath("/tagValues/", false); - uri.AppendPath(tagValue, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateValueRequest(string subscriptionId, string tagName, string tagValue) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames/", false); - uri.AppendPath(tagName, true); - uri.AppendPath("/tagValues/", false); - uri.AppendPath(tagValue, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation allows adding a value to the list of predefined values for an existing predefined tag name. A tag value can have a maximum of 256 characters. - /// The ID of the target subscription. - /// The name of the tag. - /// The value of the tag to create. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public async Task> CreateOrUpdateValueAsync(string subscriptionId, string tagName, string tagValue, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - Argument.AssertNotNullOrEmpty(tagValue, nameof(tagValue)); - - using var message = CreateCreateOrUpdateValueRequest(subscriptionId, tagName, tagValue); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 201: - { - PredefinedTagValue value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PredefinedTagValue.DeserializePredefinedTagValue(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation allows adding a value to the list of predefined values for an existing predefined tag name. A tag value can have a maximum of 256 characters. - /// The ID of the target subscription. - /// The name of the tag. - /// The value of the tag to create. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public Response CreateOrUpdateValue(string subscriptionId, string tagName, string tagValue, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - Argument.AssertNotNullOrEmpty(tagValue, nameof(tagValue)); - - using var message = CreateCreateOrUpdateValueRequest(subscriptionId, tagName, tagValue); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 201: - { - PredefinedTagValue value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PredefinedTagValue.DeserializePredefinedTagValue(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateCreateOrUpdateRequestUri(string subscriptionId, string tagName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames/", false); - uri.AppendPath(tagName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string tagName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames/", false); - uri.AppendPath(tagName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation allows adding a name to the list of predefined tag names for the given subscription. A tag name can have a maximum of 512 characters and is case-insensitive. Tag names cannot have the following prefixes which are reserved for Azure use: 'microsoft', 'azure', 'windows'. - /// The ID of the target subscription. - /// The name of the tag to create. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> CreateOrUpdateAsync(string subscriptionId, string tagName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - - using var message = CreateCreateOrUpdateRequest(subscriptionId, tagName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 201: - { - PredefinedTag value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PredefinedTag.DeserializePredefinedTag(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation allows adding a name to the list of predefined tag names for the given subscription. A tag name can have a maximum of 512 characters and is case-insensitive. Tag names cannot have the following prefixes which are reserved for Azure use: 'microsoft', 'azure', 'windows'. - /// The ID of the target subscription. - /// The name of the tag to create. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response CreateOrUpdate(string subscriptionId, string tagName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - - using var message = CreateCreateOrUpdateRequest(subscriptionId, tagName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 201: - { - PredefinedTag value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PredefinedTag.DeserializePredefinedTag(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteRequestUri(string subscriptionId, string tagName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames/", false); - uri.AppendPath(tagName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteRequest(string subscriptionId, string tagName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames/", false); - uri.AppendPath(tagName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation allows deleting a name from the list of predefined tag names for the given subscription. The name being deleted must not be in use as a tag name for any resource. All predefined values for the given name must have already been deleted. - /// The ID of the target subscription. - /// The name of the tag. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task DeleteAsync(string subscriptionId, string tagName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - - using var message = CreateDeleteRequest(subscriptionId, tagName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation allows deleting a name from the list of predefined tag names for the given subscription. The name being deleted must not be in use as a tag name for any resource. All predefined values for the given name must have already been deleted. - /// The ID of the target subscription. - /// The name of the tag. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Delete(string subscriptionId, string tagName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - - using var message = CreateDeleteRequest(subscriptionId, tagName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri(string subscriptionId) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListRequest(string subscriptionId) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation performs a union of predefined tags, resource tags, resource group tags and subscription tags, and returns a summary of usage for each tag name and value under the given subscription. In case of a large number of tags, this operation may return a previously cached result. - /// The ID of the target subscription. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListAsync(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PredefinedTagsListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PredefinedTagsListResult.DeserializePredefinedTagsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation performs a union of predefined tags, resource tags, resource group tags and subscription tags, and returns a summary of usage for each tag name and value under the given subscription. In case of a large number of tags, this operation may return a previously cached result. - /// The ID of the target subscription. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response List(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PredefinedTagsListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PredefinedTagsListResult.DeserializePredefinedTagsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateCreateOrUpdateAtScopeRequestUri(string scope, TagResourceData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Resources/tags/default", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateAtScopeRequest(string scope, TagResourceData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Resources/tags/default", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// This operation allows adding or replacing the entire set of tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags. - /// The resource scope. - /// The to use. - /// The cancellation token to use. - /// or is null. - public async Task CreateOrUpdateAtScopeAsync(string scope, TagResourceData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateAtScopeRequest(scope, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation allows adding or replacing the entire set of tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags. - /// The resource scope. - /// The to use. - /// The cancellation token to use. - /// or is null. - public Response CreateOrUpdateAtScope(string scope, TagResourceData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateAtScopeRequest(scope, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateUpdateAtScopeRequestUri(string scope, TagResourcePatch patch) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Resources/tags/default", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateUpdateAtScopeRequest(string scope, TagResourcePatch patch) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Patch; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Resources/tags/default", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(patch, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// This operation allows replacing, merging or selectively deleting tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags at the end of the operation. The 'replace' option replaces the entire set of existing tags with a new set. The 'merge' option allows adding tags with new names and updating the values of tags with existing names. The 'delete' option allows selectively deleting tags based on given names or name/value pairs. - /// The resource scope. - /// The to use. - /// The cancellation token to use. - /// or is null. - public async Task UpdateAtScopeAsync(string scope, TagResourcePatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNull(patch, nameof(patch)); - - using var message = CreateUpdateAtScopeRequest(scope, patch); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation allows replacing, merging or selectively deleting tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags at the end of the operation. The 'replace' option replaces the entire set of existing tags with a new set. The 'merge' option allows adding tags with new names and updating the values of tags with existing names. The 'delete' option allows selectively deleting tags based on given names or name/value pairs. - /// The resource scope. - /// The to use. - /// The cancellation token to use. - /// or is null. - public Response UpdateAtScope(string scope, TagResourcePatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNull(patch, nameof(patch)); - - using var message = CreateUpdateAtScopeRequest(scope, patch); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetAtScopeRequestUri(string scope) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Resources/tags/default", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetAtScopeRequest(string scope) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Resources/tags/default", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets the entire set of tags on a resource or subscription. - /// The resource scope. - /// The cancellation token to use. - /// is null. - public async Task> GetAtScopeAsync(string scope, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - - using var message = CreateGetAtScopeRequest(scope); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - TagResourceData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = TagResourceData.DeserializeTagResourceData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((TagResourceData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets the entire set of tags on a resource or subscription. - /// The resource scope. - /// The cancellation token to use. - /// is null. - public Response GetAtScope(string scope, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - - using var message = CreateGetAtScopeRequest(scope); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - TagResourceData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = TagResourceData.DeserializeTagResourceData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((TagResourceData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteAtScopeRequestUri(string scope) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Resources/tags/default", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteAtScopeRequest(string scope) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Resources/tags/default", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Deletes the entire set of tags on a resource or subscription. - /// The resource scope. - /// The cancellation token to use. - /// is null. - public async Task DeleteAtScopeAsync(string scope, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - - using var message = CreateDeleteAtScopeRequest(scope); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// Deletes the entire set of tags on a resource or subscription. - /// The resource scope. - /// The cancellation token to use. - /// is null. - public Response DeleteAtScope(string scope, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - - using var message = CreateDeleteAtScopeRequest(scope); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string subscriptionId) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation performs a union of predefined tags, resource tags, resource group tags and subscription tags, and returns a summary of usage for each tag name and value under the given subscription. In case of a large number of tags, this operation may return a previously cached result. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListNextPageAsync(string nextLink, string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PredefinedTagsListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PredefinedTagsListResult.DeserializePredefinedTagsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation performs a union of predefined tags, resource tags, resource group tags and subscription tags, and returns a summary of usage for each tag name and value under the given subscription. In case of a large number of tags, this operation may return a previously cached result. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListNextPage(string nextLink, string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PredefinedTagsListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PredefinedTagsListResult.DeserializePredefinedTagsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/TenantsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/TenantsRestOperations.cs deleted file mode 100644 index 25264b970e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/RestOperations/TenantsRestOperations.cs +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class TenantsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of TenantsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public TenantsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2022-12-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateListRequestUri() - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/tenants", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListRequest() - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/tenants", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets the tenants for your account. - /// The cancellation token to use. - public async Task> ListAsync(CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - TenantListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = TenantListResult.DeserializeTenantListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets the tenants for your account. - /// The cancellation token to use. - public Response List(CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - TenantListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = TenantListResult.DeserializeTenantListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetRequestUri() - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets the tenants for your account. - /// The URL to the next page of results. - /// The cancellation token to use. - /// is null. - public async Task> ListNextPageAsync(string nextLink, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - TenantListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = TenantListResult.DeserializeTenantListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets the tenants for your account. - /// The URL to the next page of results. - /// The cancellation token to use. - /// is null. - public Response ListNextPage(string nextLink, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - TenantListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = TenantListResult.DeserializeTenantListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionCollection.cs deleted file mode 100644 index 8ff124397b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionCollection.cs +++ /dev/null @@ -1,394 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetSubscriptions method from an instance of . - /// - public partial class SubscriptionCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _subscriptionClientDiagnostics; - private readonly SubscriptionsRestOperations _subscriptionRestClient; - - /// Initializes a new instance of the class for mocking. - protected SubscriptionCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal SubscriptionCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _subscriptionClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", SubscriptionResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(SubscriptionResource.ResourceType, out string subscriptionApiVersion); - _subscriptionRestClient = new SubscriptionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, subscriptionApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != TenantResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, TenantResource.ResourceType), nameof(id)); - } - - /// - /// Gets details about a specified subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The ID of the target subscription. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _subscriptionClientDiagnostics.CreateScope("SubscriptionCollection.Get"); - scope.Start(); - try - { - var response = await _subscriptionRestClient.GetAsync(subscriptionId, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets details about a specified subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The ID of the target subscription. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _subscriptionClientDiagnostics.CreateScope("SubscriptionCollection.Get"); - scope.Start(); - try - { - var response = _subscriptionRestClient.Get(subscriptionId, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets all subscriptions for a tenant. - /// - /// - /// Request Path - /// /subscriptions - /// - /// - /// Operation Id - /// Subscriptions_List - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionRestClient.CreateListRequest(); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _subscriptionRestClient.CreateListNextPageRequest(nextLink); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new SubscriptionResource(Client, SubscriptionData.DeserializeSubscriptionData(e)), _subscriptionClientDiagnostics, Pipeline, "SubscriptionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Gets all subscriptions for a tenant. - /// - /// - /// Request Path - /// /subscriptions - /// - /// - /// Operation Id - /// Subscriptions_List - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionRestClient.CreateListRequest(); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _subscriptionRestClient.CreateListNextPageRequest(nextLink); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new SubscriptionResource(Client, SubscriptionData.DeserializeSubscriptionData(e)), _subscriptionClientDiagnostics, Pipeline, "SubscriptionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The ID of the target subscription. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _subscriptionClientDiagnostics.CreateScope("SubscriptionCollection.Exists"); - scope.Start(); - try - { - var response = await _subscriptionRestClient.GetAsync(subscriptionId, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The ID of the target subscription. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _subscriptionClientDiagnostics.CreateScope("SubscriptionCollection.Exists"); - scope.Start(); - try - { - var response = _subscriptionRestClient.Get(subscriptionId, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The ID of the target subscription. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _subscriptionClientDiagnostics.CreateScope("SubscriptionCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _subscriptionRestClient.GetAsync(subscriptionId, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new SubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The ID of the target subscription. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _subscriptionClientDiagnostics.CreateScope("SubscriptionCollection.GetIfExists"); - scope.Start(); - try - { - var response = _subscriptionRestClient.Get(subscriptionId, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new SubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionData.Serialization.cs deleted file mode 100644 index 8574e5e3ba..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionData.Serialization.cs +++ /dev/null @@ -1,481 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class SubscriptionData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SubscriptionData)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && Optional.IsDefined(SubscriptionId)) - { - writer.WritePropertyName("subscriptionId"u8); - writer.WriteStringValue(SubscriptionId); - } - if (options.Format != "W" && Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (options.Format != "W" && Optional.IsDefined(TenantId)) - { - writer.WritePropertyName("tenantId"u8); - writer.WriteStringValue(TenantId.Value); - } - if (options.Format != "W" && Optional.IsDefined(State)) - { - writer.WritePropertyName("state"u8); - writer.WriteStringValue(State.Value.ToSerialString()); - } - if (Optional.IsDefined(SubscriptionPolicies)) - { - writer.WritePropertyName("subscriptionPolicies"u8); - writer.WriteObjectValue(SubscriptionPolicies, options); - } - if (Optional.IsDefined(AuthorizationSource)) - { - writer.WritePropertyName("authorizationSource"u8); - writer.WriteStringValue(AuthorizationSource); - } - if (Optional.IsCollectionDefined(ManagedByTenants)) - { - writer.WritePropertyName("managedByTenants"u8); - writer.WriteStartArray(); - foreach (var item in ManagedByTenants) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(Tags)) - { - writer.WritePropertyName("tags"u8); - writer.WriteStartObject(); - foreach (var item in Tags) - { - writer.WritePropertyName(item.Key); - writer.WriteStringValue(item.Value); - } - writer.WriteEndObject(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - SubscriptionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SubscriptionData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeSubscriptionData(document.RootElement, options); - } - - internal static SubscriptionData DeserializeSubscriptionData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string subscriptionId = default; - string displayName = default; - Guid? tenantId = default; - SubscriptionState? state = default; - SubscriptionPolicies subscriptionPolicies = default; - string authorizationSource = default; - IReadOnlyList managedByTenants = default; - IReadOnlyDictionary tags = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("subscriptionId"u8)) - { - subscriptionId = property.Value.GetString(); - continue; - } - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (property.NameEquals("tenantId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - tenantId = property.Value.GetGuid(); - continue; - } - if (property.NameEquals("state"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - state = property.Value.GetString().ToSubscriptionState(); - continue; - } - if (property.NameEquals("subscriptionPolicies"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - subscriptionPolicies = SubscriptionPolicies.DeserializeSubscriptionPolicies(property.Value, options); - continue; - } - if (property.NameEquals("authorizationSource"u8)) - { - authorizationSource = property.Value.GetString(); - continue; - } - if (property.NameEquals("managedByTenants"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ManagedByTenant.DeserializeManagedByTenant(item, options)); - } - managedByTenants = array; - continue; - } - if (property.NameEquals("tags"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - tags = dictionary; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new SubscriptionData( - id, - subscriptionId, - displayName, - tenantId, - state, - subscriptionPolicies, - authorizationSource, - managedByTenants ?? new ChangeTrackingList(), - tags ?? new ChangeTrackingDictionary(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SubscriptionId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" subscriptionId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SubscriptionId)) - { - builder.Append(" subscriptionId: "); - if (SubscriptionId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{SubscriptionId}'''"); - } - else - { - builder.AppendLine($"'{SubscriptionId}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TenantId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenantId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TenantId)) - { - builder.Append(" tenantId: "); - builder.AppendLine($"'{TenantId.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(State), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" state: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(State)) - { - builder.Append(" state: "); - builder.AppendLine($"'{State.Value.ToSerialString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SubscriptionPolicies), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" subscriptionPolicies: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SubscriptionPolicies)) - { - builder.Append(" subscriptionPolicies: "); - BicepSerializationHelpers.AppendChildObject(builder, SubscriptionPolicies, options, 2, false, " subscriptionPolicies: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(AuthorizationSource), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" authorizationSource: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(AuthorizationSource)) - { - builder.Append(" authorizationSource: "); - if (AuthorizationSource.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{AuthorizationSource}'''"); - } - else - { - builder.AppendLine($"'{AuthorizationSource}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ManagedByTenants), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" managedByTenants: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ManagedByTenants)) - { - if (ManagedByTenants.Any()) - { - builder.Append(" managedByTenants: "); - builder.AppendLine("["); - foreach (var item in ManagedByTenants) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " managedByTenants: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Tags), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tags: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Tags)) - { - if (Tags.Any()) - { - builder.Append(" tags: "); - builder.AppendLine("{"); - foreach (var item in Tags) - { - builder.Append($" '{item.Key}': "); - if (item.Value == null) - { - builder.Append("null"); - continue; - } - if (item.Value.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{item.Value}'''"); - } - else - { - builder.AppendLine($"'{item.Value}'"); - } - } - builder.AppendLine(" }"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(SubscriptionData)} does not support writing '{options.Format}' format."); - } - } - - SubscriptionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeSubscriptionData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(SubscriptionData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionData.cs deleted file mode 100644 index 02537ef7b6..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionData.cs +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the Subscription data model. - /// Subscription information. - /// - public partial class SubscriptionData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal SubscriptionData() - { - ManagedByTenants = new ChangeTrackingList(); - Tags = new ChangeTrackingDictionary(); - } - - /// Initializes a new instance of . - /// The fully qualified ID for the subscription. For example, /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74. - /// The subscription ID. - /// The subscription display name. - /// The subscription tenant ID. - /// The subscription state. Possible values are Enabled, Warned, PastDue, Disabled, and Deleted. - /// The subscription policies. - /// The authorization source of the request. Valid values are one or more combinations of Legacy, RoleBased, Bypassed, Direct and Management. For example, 'Legacy, RoleBased'. - /// An array containing the tenants managing the subscription. - /// The tags attached to the subscription. - /// Keeps track of any properties unknown to the library. - internal SubscriptionData(ResourceIdentifier id, string subscriptionId, string displayName, Guid? tenantId, SubscriptionState? state, SubscriptionPolicies subscriptionPolicies, string authorizationSource, IReadOnlyList managedByTenants, IReadOnlyDictionary tags, IDictionary serializedAdditionalRawData) - { - Id = id; - SubscriptionId = subscriptionId; - DisplayName = displayName; - TenantId = tenantId; - State = state; - SubscriptionPolicies = subscriptionPolicies; - AuthorizationSource = authorizationSource; - ManagedByTenants = managedByTenants; - Tags = tags; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - /// The subscription ID. - [WirePath("subscriptionId")] - public string SubscriptionId { get; } - /// The subscription display name. - [WirePath("displayName")] - public string DisplayName { get; } - /// The subscription tenant ID. - [WirePath("tenantId")] - public Guid? TenantId { get; } - /// The subscription state. Possible values are Enabled, Warned, PastDue, Disabled, and Deleted. - [WirePath("state")] - public SubscriptionState? State { get; } - /// The subscription policies. - [WirePath("subscriptionPolicies")] - public SubscriptionPolicies SubscriptionPolicies { get; } - /// The authorization source of the request. Valid values are one or more combinations of Legacy, RoleBased, Bypassed, Direct and Management. For example, 'Legacy, RoleBased'. - [WirePath("authorizationSource")] - public string AuthorizationSource { get; } - /// An array containing the tenants managing the subscription. - [WirePath("managedByTenants")] - public IReadOnlyList ManagedByTenants { get; } - /// The tags attached to the subscription. - [WirePath("tags")] - public IReadOnlyDictionary Tags { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionCollection.cs deleted file mode 100644 index e0e348db73..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionCollection.cs +++ /dev/null @@ -1,500 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetSubscriptionPolicyDefinitions method from an instance of . - /// - public partial class SubscriptionPolicyDefinitionCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics; - private readonly PolicyDefinitionsRestOperations _subscriptionPolicyDefinitionPolicyDefinitionsRestClient; - - /// Initializes a new instance of the class for mocking. - protected SubscriptionPolicyDefinitionCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal SubscriptionPolicyDefinitionCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", SubscriptionPolicyDefinitionResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(SubscriptionPolicyDefinitionResource.ResourceType, out string subscriptionPolicyDefinitionPolicyDefinitionsApiVersion); - _subscriptionPolicyDefinitionPolicyDefinitionsRestClient = new PolicyDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, subscriptionPolicyDefinitionPolicyDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != SubscriptionResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, SubscriptionResource.ResourceType), nameof(id)); - } - - /// - /// This operation creates or updates a policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy definition to create. - /// The policy definition properties. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string policyDefinitionName, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateOrUpdateAsync(Id.SubscriptionId, policyDefinitionName, data, cancellationToken).ConfigureAwait(false); - var uri = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, policyDefinitionName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy definition to create. - /// The policy definition properties. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string policyDefinitionName, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateOrUpdate(Id.SubscriptionId, policyDefinitionName, data, cancellationToken); - var uri = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, policyDefinitionName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionCollection.Get"); - scope.Start(); - try - { - var response = await _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.GetAsync(Id.SubscriptionId, policyDefinitionName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionCollection.Get"); - scope.Start(); - try - { - var response = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.Get(Id.SubscriptionId, policyDefinitionName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a list of all the policy definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions - /// - /// - /// Operation Id - /// PolicyDefinitions_List - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateListRequest(Id.SubscriptionId, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new SubscriptionPolicyDefinitionResource(Client, PolicyDefinitionData.DeserializePolicyDefinitionData(e)), _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics, Pipeline, "SubscriptionPolicyDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// This operation retrieves a list of all the policy definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions - /// - /// - /// Operation Id - /// PolicyDefinitions_List - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateListRequest(Id.SubscriptionId, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new SubscriptionPolicyDefinitionResource(Client, PolicyDefinitionData.DeserializePolicyDefinitionData(e)), _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics, Pipeline, "SubscriptionPolicyDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = await _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.GetAsync(Id.SubscriptionId, policyDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.Get(Id.SubscriptionId, policyDefinitionName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.GetAsync(Id.SubscriptionId, policyDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.Get(Id.SubscriptionId, policyDefinitionName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionResource.Serialization.cs deleted file mode 100644 index d98f9066c1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class SubscriptionPolicyDefinitionResource : IJsonModel - { - private static PolicyDefinitionData s_dataDeserializationInstance; - private static PolicyDefinitionData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - PolicyDefinitionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - PolicyDefinitionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionResource.cs deleted file mode 100644 index 415bda5437..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionResource.cs +++ /dev/null @@ -1,353 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a SubscriptionPolicyDefinition along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetSubscriptionPolicyDefinitionResource method. - /// Otherwise you can get one from its parent resource using the GetSubscriptionPolicyDefinition method. - /// - public partial class SubscriptionPolicyDefinitionResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The subscriptionId. - /// The policyDefinitionName. - public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string policyDefinitionName) - { - var resourceId = $"/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics; - private readonly PolicyDefinitionsRestOperations _subscriptionPolicyDefinitionPolicyDefinitionsRestClient; - private readonly PolicyDefinitionData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Authorization/policyDefinitions"; - - /// Initializes a new instance of the class for mocking. - protected SubscriptionPolicyDefinitionResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal SubscriptionPolicyDefinitionResource(ArmClient client, PolicyDefinitionData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal SubscriptionPolicyDefinitionResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string subscriptionPolicyDefinitionPolicyDefinitionsApiVersion); - _subscriptionPolicyDefinitionPolicyDefinitionsRestClient = new PolicyDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, subscriptionPolicyDefinitionPolicyDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual PolicyDefinitionData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionResource.Get"); - scope.Start(); - try - { - var response = await _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.GetAsync(Id.SubscriptionId, Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionResource.Get"); - scope.Start(); - try - { - var response = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.Get(Id.SubscriptionId, Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes the policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Delete - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual async Task DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionResource.Delete"); - scope.Start(); - try - { - var response = await _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.DeleteAsync(Id.SubscriptionId, Id.Name, cancellationToken).ConfigureAwait(false); - var uri = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateDeleteRequestUri(Id.SubscriptionId, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes the policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Delete - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionResource.Delete"); - scope.Start(); - try - { - var response = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.Delete(Id.SubscriptionId, Id.Name, cancellationToken); - var uri = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateDeleteRequestUri(Id.SubscriptionId, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The policy definition properties. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(WaitUntil waitUntil, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionResource.Update"); - scope.Start(); - try - { - var response = await _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.Name, data, cancellationToken).ConfigureAwait(false); - var uri = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The policy definition properties. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation Update(WaitUntil waitUntil, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionResource.Update"); - scope.Start(); - try - { - var response = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateOrUpdate(Id.SubscriptionId, Id.Name, data, cancellationToken); - var uri = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionCollection.cs deleted file mode 100644 index 3f7c59a96f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionCollection.cs +++ /dev/null @@ -1,500 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetSubscriptionPolicySetDefinitions method from an instance of . - /// - public partial class SubscriptionPolicySetDefinitionCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics; - private readonly PolicySetDefinitionsRestOperations _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient; - - /// Initializes a new instance of the class for mocking. - protected SubscriptionPolicySetDefinitionCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal SubscriptionPolicySetDefinitionCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", SubscriptionPolicySetDefinitionResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(SubscriptionPolicySetDefinitionResource.ResourceType, out string subscriptionPolicySetDefinitionPolicySetDefinitionsApiVersion); - _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient = new PolicySetDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, subscriptionPolicySetDefinitionPolicySetDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != SubscriptionResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, SubscriptionResource.ResourceType), nameof(id)); - } - - /// - /// This operation creates or updates a policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy set definition to create. - /// The policy set definition properties. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string policySetDefinitionName, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateOrUpdateAsync(Id.SubscriptionId, policySetDefinitionName, data, cancellationToken).ConfigureAwait(false); - var uri = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, policySetDefinitionName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy set definition to create. - /// The policy set definition properties. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string policySetDefinitionName, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateOrUpdate(Id.SubscriptionId, policySetDefinitionName, data, cancellationToken); - var uri = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, policySetDefinitionName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionCollection.Get"); - scope.Start(); - try - { - var response = await _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.GetAsync(Id.SubscriptionId, policySetDefinitionName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionCollection.Get"); - scope.Start(); - try - { - var response = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.Get(Id.SubscriptionId, policySetDefinitionName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a list of all the policy set definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions - /// - /// - /// Operation Id - /// PolicySetDefinitions_List - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListRequest(Id.SubscriptionId, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new SubscriptionPolicySetDefinitionResource(Client, PolicySetDefinitionData.DeserializePolicySetDefinitionData(e)), _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics, Pipeline, "SubscriptionPolicySetDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// This operation retrieves a list of all the policy set definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions - /// - /// - /// Operation Id - /// PolicySetDefinitions_List - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListRequest(Id.SubscriptionId, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new SubscriptionPolicySetDefinitionResource(Client, PolicySetDefinitionData.DeserializePolicySetDefinitionData(e)), _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics, Pipeline, "SubscriptionPolicySetDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = await _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.GetAsync(Id.SubscriptionId, policySetDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.Get(Id.SubscriptionId, policySetDefinitionName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.GetAsync(Id.SubscriptionId, policySetDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.Get(Id.SubscriptionId, policySetDefinitionName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionResource.Serialization.cs deleted file mode 100644 index 2c9efcff84..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class SubscriptionPolicySetDefinitionResource : IJsonModel - { - private static PolicySetDefinitionData s_dataDeserializationInstance; - private static PolicySetDefinitionData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - PolicySetDefinitionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - PolicySetDefinitionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionResource.cs deleted file mode 100644 index 9bf306c256..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionResource.cs +++ /dev/null @@ -1,353 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a SubscriptionPolicySetDefinition along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetSubscriptionPolicySetDefinitionResource method. - /// Otherwise you can get one from its parent resource using the GetSubscriptionPolicySetDefinition method. - /// - public partial class SubscriptionPolicySetDefinitionResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The subscriptionId. - /// The policySetDefinitionName. - public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string policySetDefinitionName) - { - var resourceId = $"/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics; - private readonly PolicySetDefinitionsRestOperations _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient; - private readonly PolicySetDefinitionData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Authorization/policySetDefinitions"; - - /// Initializes a new instance of the class for mocking. - protected SubscriptionPolicySetDefinitionResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal SubscriptionPolicySetDefinitionResource(ArmClient client, PolicySetDefinitionData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal SubscriptionPolicySetDefinitionResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string subscriptionPolicySetDefinitionPolicySetDefinitionsApiVersion); - _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient = new PolicySetDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, subscriptionPolicySetDefinitionPolicySetDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual PolicySetDefinitionData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionResource.Get"); - scope.Start(); - try - { - var response = await _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.GetAsync(Id.SubscriptionId, Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionResource.Get"); - scope.Start(); - try - { - var response = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.Get(Id.SubscriptionId, Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes the policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Delete - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual async Task DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionResource.Delete"); - scope.Start(); - try - { - var response = await _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.DeleteAsync(Id.SubscriptionId, Id.Name, cancellationToken).ConfigureAwait(false); - var uri = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateDeleteRequestUri(Id.SubscriptionId, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes the policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Delete - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionResource.Delete"); - scope.Start(); - try - { - var response = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.Delete(Id.SubscriptionId, Id.Name, cancellationToken); - var uri = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateDeleteRequestUri(Id.SubscriptionId, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The policy set definition properties. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(WaitUntil waitUntil, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionResource.Update"); - scope.Start(); - try - { - var response = await _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.Name, data, cancellationToken).ConfigureAwait(false); - var uri = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The policy set definition properties. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation Update(WaitUntil waitUntil, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionResource.Update"); - scope.Start(); - try - { - var response = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateOrUpdate(Id.SubscriptionId, Id.Name, data, cancellationToken); - var uri = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionResource.Serialization.cs deleted file mode 100644 index 138601640e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class SubscriptionResource : IJsonModel - { - private static SubscriptionData s_dataDeserializationInstance; - private static SubscriptionData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - SubscriptionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - SubscriptionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionResource.cs deleted file mode 100644 index e484fd200a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/SubscriptionResource.cs +++ /dev/null @@ -1,962 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a Subscription along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetSubscriptionResource method. - /// Otherwise you can get one from its parent resource using the GetSubscription method. - /// - public partial class SubscriptionResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The subscriptionId. - public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId) - { - var resourceId = $"/subscriptions/{subscriptionId}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _subscriptionClientDiagnostics; - private readonly SubscriptionsRestOperations _subscriptionRestClient; - private readonly ClientDiagnostics _subscriptionResourcesClientDiagnostics; - private readonly ResourcesRestOperations _subscriptionResourcesRestClient; - private readonly ClientDiagnostics _subscriptionTagsClientDiagnostics; - private readonly TagsRestOperations _subscriptionTagsRestClient; - private readonly ClientDiagnostics _featureClientDiagnostics; - private readonly FeaturesRestOperations _featureRestClient; - private readonly SubscriptionData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Resources/subscriptions"; - - /// Initializes a new instance of the class for mocking. - protected SubscriptionResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal SubscriptionResource(ArmClient client, SubscriptionData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal SubscriptionResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _subscriptionClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string subscriptionApiVersion); - _subscriptionRestClient = new SubscriptionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, subscriptionApiVersion); - _subscriptionResourcesClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string subscriptionResourcesApiVersion); - _subscriptionResourcesRestClient = new ResourcesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, subscriptionResourcesApiVersion); - _subscriptionTagsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string subscriptionTagsApiVersion); - _subscriptionTagsRestClient = new TagsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, subscriptionTagsApiVersion); - _featureClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", FeatureResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(FeatureResource.ResourceType, out string featureApiVersion); - _featureRestClient = new FeaturesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, featureApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual SubscriptionData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// Gets a collection of SubscriptionPolicyDefinitionResources in the Subscription. - /// An object representing collection of SubscriptionPolicyDefinitionResources and their operations over a SubscriptionPolicyDefinitionResource. - public virtual SubscriptionPolicyDefinitionCollection GetSubscriptionPolicyDefinitions() - { - return GetCachedClient(client => new SubscriptionPolicyDefinitionCollection(client, Id)); - } - - /// - /// This operation retrieves the policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetSubscriptionPolicyDefinitionAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - return await GetSubscriptionPolicyDefinitions().GetAsync(policyDefinitionName, cancellationToken).ConfigureAwait(false); - } - - /// - /// This operation retrieves the policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetSubscriptionPolicyDefinition(string policyDefinitionName, CancellationToken cancellationToken = default) - { - return GetSubscriptionPolicyDefinitions().Get(policyDefinitionName, cancellationToken); - } - - /// Gets a collection of SubscriptionPolicySetDefinitionResources in the Subscription. - /// An object representing collection of SubscriptionPolicySetDefinitionResources and their operations over a SubscriptionPolicySetDefinitionResource. - public virtual SubscriptionPolicySetDefinitionCollection GetSubscriptionPolicySetDefinitions() - { - return GetCachedClient(client => new SubscriptionPolicySetDefinitionCollection(client, Id)); - } - - /// - /// This operation retrieves the policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetSubscriptionPolicySetDefinitionAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - return await GetSubscriptionPolicySetDefinitions().GetAsync(policySetDefinitionName, cancellationToken).ConfigureAwait(false); - } - - /// - /// This operation retrieves the policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetSubscriptionPolicySetDefinition(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - return GetSubscriptionPolicySetDefinitions().Get(policySetDefinitionName, cancellationToken); - } - - /// Gets a collection of ResourceProviderResources in the Subscription. - /// An object representing collection of ResourceProviderResources and their operations over a ResourceProviderResource. - public virtual ResourceProviderCollection GetResourceProviders() - { - return GetCachedClient(client => new ResourceProviderCollection(client, Id)); - } - - /// - /// Gets the specified resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetResourceProviderAsync(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - return await GetResourceProviders().GetAsync(resourceProviderNamespace, expand, cancellationToken).ConfigureAwait(false); - } - - /// - /// Gets the specified resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetResourceProvider(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - return GetResourceProviders().Get(resourceProviderNamespace, expand, cancellationToken); - } - - /// Gets a collection of ResourceGroupResources in the Subscription. - /// An object representing collection of ResourceGroupResources and their operations over a ResourceGroupResource. - public virtual ResourceGroupCollection GetResourceGroups() - { - return GetCachedClient(client => new ResourceGroupCollection(client, Id)); - } - - /// - /// Gets a resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetResourceGroupAsync(string resourceGroupName, CancellationToken cancellationToken = default) - { - return await GetResourceGroups().GetAsync(resourceGroupName, cancellationToken).ConfigureAwait(false); - } - - /// - /// Gets a resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetResourceGroup(string resourceGroupName, CancellationToken cancellationToken = default) - { - return GetResourceGroups().Get(resourceGroupName, cancellationToken); - } - - /// - /// Gets details about a specified subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _subscriptionClientDiagnostics.CreateScope("SubscriptionResource.Get"); - scope.Start(); - try - { - var response = await _subscriptionRestClient.GetAsync(Id.SubscriptionId, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets details about a specified subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _subscriptionClientDiagnostics.CreateScope("SubscriptionResource.Get"); - scope.Start(); - try - { - var response = _subscriptionRestClient.Get(Id.SubscriptionId, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows deleting a value from the list of predefined values for an existing predefined tag name. The value being deleted must not be in use as a tag value for the given tag name for any resource. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames/{tagName}/tagValues/{tagValue} - /// - /// - /// Operation Id - /// Tags_DeleteValue - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The name of the tag. - /// The value of the tag to delete. - /// The cancellation token to use. - /// or is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task DeletePredefinedTagValueAsync(string tagName, string tagValue, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - Argument.AssertNotNullOrEmpty(tagValue, nameof(tagValue)); - - using var scope = _subscriptionTagsClientDiagnostics.CreateScope("SubscriptionResource.DeletePredefinedTagValue"); - scope.Start(); - try - { - var response = await _subscriptionTagsRestClient.DeleteValueAsync(Id.SubscriptionId, tagName, tagValue, cancellationToken).ConfigureAwait(false); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows deleting a value from the list of predefined values for an existing predefined tag name. The value being deleted must not be in use as a tag value for the given tag name for any resource. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames/{tagName}/tagValues/{tagValue} - /// - /// - /// Operation Id - /// Tags_DeleteValue - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The name of the tag. - /// The value of the tag to delete. - /// The cancellation token to use. - /// or is an empty string, and was expected to be non-empty. - /// or is null. - public virtual Response DeletePredefinedTagValue(string tagName, string tagValue, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - Argument.AssertNotNullOrEmpty(tagValue, nameof(tagValue)); - - using var scope = _subscriptionTagsClientDiagnostics.CreateScope("SubscriptionResource.DeletePredefinedTagValue"); - scope.Start(); - try - { - var response = _subscriptionTagsRestClient.DeleteValue(Id.SubscriptionId, tagName, tagValue, cancellationToken); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows adding a value to the list of predefined values for an existing predefined tag name. A tag value can have a maximum of 256 characters. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames/{tagName}/tagValues/{tagValue} - /// - /// - /// Operation Id - /// Tags_CreateOrUpdateValue - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The name of the tag. - /// The value of the tag to create. - /// The cancellation token to use. - /// or is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task> CreateOrUpdatePredefinedTagValueAsync(string tagName, string tagValue, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - Argument.AssertNotNullOrEmpty(tagValue, nameof(tagValue)); - - using var scope = _subscriptionTagsClientDiagnostics.CreateScope("SubscriptionResource.CreateOrUpdatePredefinedTagValue"); - scope.Start(); - try - { - var response = await _subscriptionTagsRestClient.CreateOrUpdateValueAsync(Id.SubscriptionId, tagName, tagValue, cancellationToken).ConfigureAwait(false); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows adding a value to the list of predefined values for an existing predefined tag name. A tag value can have a maximum of 256 characters. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames/{tagName}/tagValues/{tagValue} - /// - /// - /// Operation Id - /// Tags_CreateOrUpdateValue - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The name of the tag. - /// The value of the tag to create. - /// The cancellation token to use. - /// or is an empty string, and was expected to be non-empty. - /// or is null. - public virtual Response CreateOrUpdatePredefinedTagValue(string tagName, string tagValue, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - Argument.AssertNotNullOrEmpty(tagValue, nameof(tagValue)); - - using var scope = _subscriptionTagsClientDiagnostics.CreateScope("SubscriptionResource.CreateOrUpdatePredefinedTagValue"); - scope.Start(); - try - { - var response = _subscriptionTagsRestClient.CreateOrUpdateValue(Id.SubscriptionId, tagName, tagValue, cancellationToken); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows adding a name to the list of predefined tag names for the given subscription. A tag name can have a maximum of 512 characters and is case-insensitive. Tag names cannot have the following prefixes which are reserved for Azure use: 'microsoft', 'azure', 'windows'. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames/{tagName} - /// - /// - /// Operation Id - /// Tags_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The name of the tag to create. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> CreateOrUpdatePredefinedTagAsync(string tagName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - - using var scope = _subscriptionTagsClientDiagnostics.CreateScope("SubscriptionResource.CreateOrUpdatePredefinedTag"); - scope.Start(); - try - { - var response = await _subscriptionTagsRestClient.CreateOrUpdateAsync(Id.SubscriptionId, tagName, cancellationToken).ConfigureAwait(false); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows adding a name to the list of predefined tag names for the given subscription. A tag name can have a maximum of 512 characters and is case-insensitive. Tag names cannot have the following prefixes which are reserved for Azure use: 'microsoft', 'azure', 'windows'. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames/{tagName} - /// - /// - /// Operation Id - /// Tags_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The name of the tag to create. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response CreateOrUpdatePredefinedTag(string tagName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - - using var scope = _subscriptionTagsClientDiagnostics.CreateScope("SubscriptionResource.CreateOrUpdatePredefinedTag"); - scope.Start(); - try - { - var response = _subscriptionTagsRestClient.CreateOrUpdate(Id.SubscriptionId, tagName, cancellationToken); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows deleting a name from the list of predefined tag names for the given subscription. The name being deleted must not be in use as a tag name for any resource. All predefined values for the given name must have already been deleted. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames/{tagName} - /// - /// - /// Operation Id - /// Tags_Delete - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The name of the tag. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task DeletePredefinedTagAsync(string tagName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - - using var scope = _subscriptionTagsClientDiagnostics.CreateScope("SubscriptionResource.DeletePredefinedTag"); - scope.Start(); - try - { - var response = await _subscriptionTagsRestClient.DeleteAsync(Id.SubscriptionId, tagName, cancellationToken).ConfigureAwait(false); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows deleting a name from the list of predefined tag names for the given subscription. The name being deleted must not be in use as a tag name for any resource. All predefined values for the given name must have already been deleted. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames/{tagName} - /// - /// - /// Operation Id - /// Tags_Delete - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The name of the tag. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response DeletePredefinedTag(string tagName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - - using var scope = _subscriptionTagsClientDiagnostics.CreateScope("SubscriptionResource.DeletePredefinedTag"); - scope.Start(); - try - { - var response = _subscriptionTagsRestClient.Delete(Id.SubscriptionId, tagName, cancellationToken); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation performs a union of predefined tags, resource tags, resource group tags and subscription tags, and returns a summary of usage for each tag name and value under the given subscription. In case of a large number of tags, this operation may return a previously cached result. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames - /// - /// - /// Operation Id - /// Tags_List - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllPredefinedTagsAsync(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionTagsRestClient.CreateListRequest(Id.SubscriptionId); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _subscriptionTagsRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => PredefinedTag.DeserializePredefinedTag(e), _subscriptionTagsClientDiagnostics, Pipeline, "SubscriptionResource.GetAllPredefinedTags", "value", "nextLink", cancellationToken); - } - - /// - /// This operation performs a union of predefined tags, resource tags, resource group tags and subscription tags, and returns a summary of usage for each tag name and value under the given subscription. In case of a large number of tags, this operation may return a previously cached result. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames - /// - /// - /// Operation Id - /// Tags_List - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAllPredefinedTags(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionTagsRestClient.CreateListRequest(Id.SubscriptionId); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _subscriptionTagsRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => PredefinedTag.DeserializePredefinedTag(e), _subscriptionTagsClientDiagnostics, Pipeline, "SubscriptionResource.GetAllPredefinedTags", "value", "nextLink", cancellationToken); - } - - /// - /// This operation provides all the locations that are available for resource providers; however, each resource provider may support a subset of this list. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/locations - /// - /// - /// Operation Id - /// Subscriptions_ListLocations - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Whether to include extended locations. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetLocationsAsync(bool? includeExtendedLocations = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionRestClient.CreateListLocationsRequest(Id.SubscriptionId, includeExtendedLocations); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, null, e => LocationExpanded.DeserializeLocationExpanded(e), _subscriptionClientDiagnostics, Pipeline, "SubscriptionResource.GetLocations", "value", null, cancellationToken); - } - - /// - /// This operation provides all the locations that are available for resource providers; however, each resource provider may support a subset of this list. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/locations - /// - /// - /// Operation Id - /// Subscriptions_ListLocations - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Whether to include extended locations. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetLocations(bool? includeExtendedLocations = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionRestClient.CreateListLocationsRequest(Id.SubscriptionId, includeExtendedLocations); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, null, e => LocationExpanded.DeserializeLocationExpanded(e), _subscriptionClientDiagnostics, Pipeline, "SubscriptionResource.GetLocations", "value", null, cancellationToken); - } - - /// - /// Gets all the preview features that are available through AFEC for the subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/features - /// - /// - /// Operation Id - /// Features_ListAll - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetFeaturesAsync(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _featureRestClient.CreateListAllRequest(Id.SubscriptionId); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _featureRestClient.CreateListAllNextPageRequest(nextLink, Id.SubscriptionId); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new FeatureResource(Client, FeatureData.DeserializeFeatureData(e)), _featureClientDiagnostics, Pipeline, "SubscriptionResource.GetFeatures", "value", "nextLink", cancellationToken); - } - - /// - /// Gets all the preview features that are available through AFEC for the subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/features - /// - /// - /// Operation Id - /// Features_ListAll - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetFeatures(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _featureRestClient.CreateListAllRequest(Id.SubscriptionId); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _featureRestClient.CreateListAllNextPageRequest(nextLink, Id.SubscriptionId); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new FeatureResource(Client, FeatureData.DeserializeFeatureData(e)), _featureClientDiagnostics, Pipeline, "SubscriptionResource.GetFeatures", "value", "nextLink", cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TagResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TagResource.Serialization.cs deleted file mode 100644 index 14b43eb7c4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TagResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class TagResource : IJsonModel - { - private static TagResourceData s_dataDeserializationInstance; - private static TagResourceData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - TagResourceData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - TagResourceData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TagResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TagResource.cs deleted file mode 100644 index f63e4775de..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TagResource.cs +++ /dev/null @@ -1,437 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a TagResource along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetTagResource method. - /// Otherwise you can get one from its parent resource using the GetTagResource method. - /// - public partial class TagResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The scope. - public static ResourceIdentifier CreateResourceIdentifier(string scope) - { - var resourceId = $"{scope}/providers/Microsoft.Resources/tags/default"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _tagResourceTagsClientDiagnostics; - private readonly TagsRestOperations _tagResourceTagsRestClient; - private readonly TagResourceData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Resources/tags"; - - /// Initializes a new instance of the class for mocking. - protected TagResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal TagResource(ArmClient client, TagResourceData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal TagResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _tagResourceTagsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string tagResourceTagsApiVersion); - _tagResourceTagsRestClient = new TagsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, tagResourceTagsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual TagResourceData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// Gets the entire set of tags on a resource or subscription. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_GetAtScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _tagResourceTagsClientDiagnostics.CreateScope("TagResource.Get"); - scope.Start(); - try - { - var response = await _tagResourceTagsRestClient.GetAtScopeAsync(Id.Parent, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TagResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets the entire set of tags on a resource or subscription. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_GetAtScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _tagResourceTagsClientDiagnostics.CreateScope("TagResource.Get"); - scope.Start(); - try - { - var response = _tagResourceTagsRestClient.GetAtScope(Id.Parent, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TagResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Deletes the entire set of tags on a resource or subscription. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_DeleteAtScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual async Task DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _tagResourceTagsClientDiagnostics.CreateScope("TagResource.Delete"); - scope.Start(); - try - { - var response = await _tagResourceTagsRestClient.DeleteAtScopeAsync(Id.Parent, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(_tagResourceTagsClientDiagnostics, Pipeline, _tagResourceTagsRestClient.CreateDeleteAtScopeRequest(Id.Parent).Request, response, OperationFinalStateVia.Location, skipApiVersionOverride: true); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Deletes the entire set of tags on a resource or subscription. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_DeleteAtScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _tagResourceTagsClientDiagnostics.CreateScope("TagResource.Delete"); - scope.Start(); - try - { - var response = _tagResourceTagsRestClient.DeleteAtScope(Id.Parent, cancellationToken); - var operation = new ResourcesArmOperation(_tagResourceTagsClientDiagnostics, Pipeline, _tagResourceTagsRestClient.CreateDeleteAtScopeRequest(Id.Parent).Request, response, OperationFinalStateVia.Location, skipApiVersionOverride: true); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows replacing, merging or selectively deleting tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags at the end of the operation. The 'replace' option replaces the entire set of existing tags with a new set. The 'merge' option allows adding tags with new names and updating the values of tags with existing names. The 'delete' option allows selectively deleting tags based on given names or name/value pairs. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_UpdateAtScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The to use. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(WaitUntil waitUntil, TagResourcePatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(patch, nameof(patch)); - - using var scope = _tagResourceTagsClientDiagnostics.CreateScope("TagResource.Update"); - scope.Start(); - try - { - var response = await _tagResourceTagsRestClient.UpdateAtScopeAsync(Id.Parent, patch, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(new TagResourceOperationSource(Client), _tagResourceTagsClientDiagnostics, Pipeline, _tagResourceTagsRestClient.CreateUpdateAtScopeRequest(Id.Parent, patch).Request, response, OperationFinalStateVia.Location, skipApiVersionOverride: true); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows replacing, merging or selectively deleting tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags at the end of the operation. The 'replace' option replaces the entire set of existing tags with a new set. The 'merge' option allows adding tags with new names and updating the values of tags with existing names. The 'delete' option allows selectively deleting tags based on given names or name/value pairs. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_UpdateAtScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The to use. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation Update(WaitUntil waitUntil, TagResourcePatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(patch, nameof(patch)); - - using var scope = _tagResourceTagsClientDiagnostics.CreateScope("TagResource.Update"); - scope.Start(); - try - { - var response = _tagResourceTagsRestClient.UpdateAtScope(Id.Parent, patch, cancellationToken); - var operation = new ResourcesArmOperation(new TagResourceOperationSource(Client), _tagResourceTagsClientDiagnostics, Pipeline, _tagResourceTagsRestClient.CreateUpdateAtScopeRequest(Id.Parent, patch).Request, response, OperationFinalStateVia.Location, skipApiVersionOverride: true); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows adding or replacing the entire set of tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_CreateOrUpdateAtScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The to use. - /// The cancellation token to use. - /// is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, TagResourceData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _tagResourceTagsClientDiagnostics.CreateScope("TagResource.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _tagResourceTagsRestClient.CreateOrUpdateAtScopeAsync(Id.Parent, data, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(new TagResourceOperationSource(Client), _tagResourceTagsClientDiagnostics, Pipeline, _tagResourceTagsRestClient.CreateCreateOrUpdateAtScopeRequest(Id.Parent, data).Request, response, OperationFinalStateVia.Location, skipApiVersionOverride: true); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows adding or replacing the entire set of tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_CreateOrUpdateAtScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The to use. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, TagResourceData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _tagResourceTagsClientDiagnostics.CreateScope("TagResource.CreateOrUpdate"); - scope.Start(); - try - { - var response = _tagResourceTagsRestClient.CreateOrUpdateAtScope(Id.Parent, data, cancellationToken); - var operation = new ResourcesArmOperation(new TagResourceOperationSource(Client), _tagResourceTagsClientDiagnostics, Pipeline, _tagResourceTagsRestClient.CreateCreateOrUpdateAtScopeRequest(Id.Parent, data).Request, response, OperationFinalStateVia.Location, skipApiVersionOverride: true); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TagResourceData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TagResourceData.Serialization.cs deleted file mode 100644 index 20fac26bfb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TagResourceData.Serialization.cs +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class TagResourceData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TagResourceData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("properties"u8); - writer.WriteObjectValue(Properties, options); - } - - TagResourceData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TagResourceData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeTagResourceData(document.RootElement, options); - } - - internal static TagResourceData DeserializeTagResourceData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - Tag properties = default; - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("properties"u8)) - { - properties = Tag.DeserializeTag(property.Value, options); - continue; - } - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText(), ResourceManagerJsonContext.Default.SystemData); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new TagResourceData( - id, - name, - type, - systemData, - properties, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue("TagValues", out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" properties: "); - builder.AppendLine("{"); - builder.Append(" tags: "); - builder.AppendLine(propertyOverride); - builder.AppendLine(" }"); - } - else - { - if (Optional.IsDefined(Properties)) - { - builder.Append(" properties: "); - BicepSerializationHelpers.AppendChildObject(builder, Properties, options, 2, false, " properties: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(TagResourceData)} does not support writing '{options.Format}' format."); - } - } - - TagResourceData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeTagResourceData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(TagResourceData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TagResourceData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TagResourceData.cs deleted file mode 100644 index 8bda3dfa58..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TagResourceData.cs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the TagResource data model. - /// Wrapper resource for tags API requests and responses. - /// - public partial class TagResourceData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The set of tags. - /// is null. - public TagResourceData(Tag properties) - { - Argument.AssertNotNull(properties, nameof(properties)); - - Properties = properties; - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The set of tags. - /// Keeps track of any properties unknown to the library. - internal TagResourceData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, Tag properties, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - Properties = properties; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal TagResourceData() - { - } - - /// The set of tags. - internal Tag Properties { get; set; } - /// Dictionary of <string>. - [WirePath("properties.tags")] - public IDictionary TagValues - { - get - { - if (Properties is null) - Properties = new Tag(); - return Properties.TagValues; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantCollection.cs deleted file mode 100644 index 53cd523d8b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantCollection.cs +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// A class representing a collection of and their operations. - public partial class TenantCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _tenantClientDiagnostics; - private readonly TenantsRestOperations _tenantRestClient; - private readonly ClientDiagnostics _defaultClientDiagnostics; - private readonly ResourceManagementRestOperations _defaultRestClient; - - /// Initializes a new instance of the class for mocking. - protected TenantCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal TenantCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _tenantClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", TenantResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(TenantResource.ResourceType, out string tenantApiVersion); - _tenantRestClient = new TenantsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, tenantApiVersion); - _defaultClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ProviderConstants.DefaultProviderNamespace, Diagnostics); - _defaultRestClient = new ResourceManagementRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != TenantResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, TenantResource.ResourceType), nameof(id)); - } - - /// - /// Gets the tenants for your account. - /// - /// - /// Request Path - /// /tenants - /// - /// - /// Operation Id - /// Tenants_List - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _tenantRestClient.CreateListRequest(); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _tenantRestClient.CreateListNextPageRequest(nextLink); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new TenantResource(Client, TenantData.DeserializeTenantData(e)), _tenantClientDiagnostics, Pipeline, "TenantCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Gets the tenants for your account. - /// - /// - /// Request Path - /// /tenants - /// - /// - /// Operation Id - /// Tenants_List - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _tenantRestClient.CreateListRequest(); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _tenantRestClient.CreateListNextPageRequest(nextLink); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new TenantResource(Client, TenantData.DeserializeTenantData(e)), _tenantClientDiagnostics, Pipeline, "TenantCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// A resource name is valid if it is not a reserved word, does not contains a reserved word and does not start with a reserved word - /// - /// - /// Request Path - /// /providers/Microsoft.Resources/checkResourceName - /// - /// - /// Operation Id - /// CheckResourceName - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// - /// Resource object with values for resource name and resource type. - /// The cancellation token to use. - public virtual async Task> CheckResourceNameAsync(ResourceNameValidationContent content = null, CancellationToken cancellationToken = default) - { - using var scope = _defaultClientDiagnostics.CreateScope("TenantCollection.CheckResourceName"); - scope.Start(); - try - { - var response = await _defaultRestClient.CheckResourceNameAsync(content, cancellationToken).ConfigureAwait(false); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// A resource name is valid if it is not a reserved word, does not contains a reserved word and does not start with a reserved word - /// - /// - /// Request Path - /// /providers/Microsoft.Resources/checkResourceName - /// - /// - /// Operation Id - /// CheckResourceName - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// - /// Resource object with values for resource name and resource type. - /// The cancellation token to use. - public virtual Response CheckResourceName(ResourceNameValidationContent content = null, CancellationToken cancellationToken = default) - { - using var scope = _defaultClientDiagnostics.CreateScope("TenantCollection.CheckResourceName"); - scope.Start(); - try - { - var response = _defaultRestClient.CheckResourceName(content, cancellationToken); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantData.Serialization.cs deleted file mode 100644 index 46a0ba5c76..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantData.Serialization.cs +++ /dev/null @@ -1,504 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class TenantData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TenantData)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && Optional.IsDefined(TenantId)) - { - writer.WritePropertyName("tenantId"u8); - writer.WriteStringValue(TenantId.Value); - } - if (options.Format != "W" && Optional.IsDefined(TenantCategory)) - { - writer.WritePropertyName("tenantCategory"u8); - writer.WriteStringValue(TenantCategory.Value.ToSerialString()); - } - if (options.Format != "W" && Optional.IsDefined(Country)) - { - writer.WritePropertyName("country"u8); - writer.WriteStringValue(Country); - } - if (options.Format != "W" && Optional.IsDefined(CountryCode)) - { - writer.WritePropertyName("countryCode"u8); - writer.WriteStringValue(CountryCode); - } - if (options.Format != "W" && Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (options.Format != "W" && Optional.IsCollectionDefined(Domains)) - { - writer.WritePropertyName("domains"u8); - writer.WriteStartArray(); - foreach (var item in Domains) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(DefaultDomain)) - { - writer.WritePropertyName("defaultDomain"u8); - writer.WriteStringValue(DefaultDomain); - } - if (options.Format != "W" && Optional.IsDefined(TenantType)) - { - writer.WritePropertyName("tenantType"u8); - writer.WriteStringValue(TenantType); - } - if (options.Format != "W" && Optional.IsDefined(TenantBrandingLogoUri)) - { - writer.WritePropertyName("tenantBrandingLogoUrl"u8); - writer.WriteStringValue(TenantBrandingLogoUri.AbsoluteUri); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement, ResourceManagerJsonContext.Default.JsonElement); - } -#endif - } - } - } - - TenantData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TenantData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeTenantData(document.RootElement, options); - } - - internal static TenantData DeserializeTenantData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string id = default; - Guid? tenantId = default; - TenantCategory? tenantCategory = default; - string country = default; - string countryCode = default; - string displayName = default; - IReadOnlyList domains = default; - string defaultDomain = default; - string tenantType = default; - Uri tenantBrandingLogoUrl = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("tenantId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - tenantId = property.Value.GetGuid(); - continue; - } - if (property.NameEquals("tenantCategory"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - tenantCategory = property.Value.GetString().ToTenantCategory(); - continue; - } - if (property.NameEquals("country"u8)) - { - country = property.Value.GetString(); - continue; - } - if (property.NameEquals("countryCode"u8)) - { - countryCode = property.Value.GetString(); - continue; - } - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (property.NameEquals("domains"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - domains = array; - continue; - } - if (property.NameEquals("defaultDomain"u8)) - { - defaultDomain = property.Value.GetString(); - continue; - } - if (property.NameEquals("tenantType"u8)) - { - tenantType = property.Value.GetString(); - continue; - } - if (property.NameEquals("tenantBrandingLogoUrl"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - tenantBrandingLogoUrl = new Uri(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new TenantData( - id, - tenantId, - tenantCategory, - country, - countryCode, - displayName, - domains ?? new ChangeTrackingList(), - defaultDomain, - tenantType, - tenantBrandingLogoUrl, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - if (Id.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Id}'''"); - } - else - { - builder.AppendLine($"'{Id}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TenantId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenantId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TenantId)) - { - builder.Append(" tenantId: "); - builder.AppendLine($"'{TenantId.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TenantCategory), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenantCategory: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TenantCategory)) - { - builder.Append(" tenantCategory: "); - builder.AppendLine($"'{TenantCategory.Value.ToSerialString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Country), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" country: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Country)) - { - builder.Append(" country: "); - if (Country.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Country}'''"); - } - else - { - builder.AppendLine($"'{Country}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(CountryCode), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" countryCode: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(CountryCode)) - { - builder.Append(" countryCode: "); - if (CountryCode.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{CountryCode}'''"); - } - else - { - builder.AppendLine($"'{CountryCode}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Domains), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" domains: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Domains)) - { - if (Domains.Any()) - { - builder.Append(" domains: "); - builder.AppendLine("["); - foreach (var item in Domains) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DefaultDomain), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" defaultDomain: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DefaultDomain)) - { - builder.Append(" defaultDomain: "); - if (DefaultDomain.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DefaultDomain}'''"); - } - else - { - builder.AppendLine($"'{DefaultDomain}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TenantType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenantType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TenantType)) - { - builder.Append(" tenantType: "); - if (TenantType.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{TenantType}'''"); - } - else - { - builder.AppendLine($"'{TenantType}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TenantBrandingLogoUri), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenantBrandingLogoUrl: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TenantBrandingLogoUri)) - { - builder.Append(" tenantBrandingLogoUrl: "); - builder.AppendLine($"'{TenantBrandingLogoUri.AbsoluteUri}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(TenantData)} does not support writing '{options.Format}' format."); - } - } - - TenantData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeTenantData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(TenantData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantData.cs deleted file mode 100644 index 7d91999217..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantData.cs +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the Tenant data model. - /// Tenant Id information. - /// - public partial class TenantData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal TenantData() - { - Domains = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The fully qualified ID of the tenant. For example, /tenants/8d65815f-a5b6-402f-9298-045155da7d74. - /// The tenant ID. For example, 8d65815f-a5b6-402f-9298-045155da7d74. - /// Category of the tenant. - /// Country/region name of the address for the tenant. - /// Country/region abbreviation for the tenant. - /// The display name of the tenant. - /// The list of domains for the tenant. - /// The default domain for the tenant. - /// The tenant type. Only available for 'Home' tenant category. - /// The tenant's branding logo URL. Only available for 'Home' tenant category. - /// Keeps track of any properties unknown to the library. - internal TenantData(string id, Guid? tenantId, TenantCategory? tenantCategory, string country, string countryCode, string displayName, IReadOnlyList domains, string defaultDomain, string tenantType, Uri tenantBrandingLogoUri, IDictionary serializedAdditionalRawData) - { - Id = id; - TenantId = tenantId; - TenantCategory = tenantCategory; - Country = country; - CountryCode = countryCode; - DisplayName = displayName; - Domains = domains; - DefaultDomain = defaultDomain; - TenantType = tenantType; - TenantBrandingLogoUri = tenantBrandingLogoUri; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The fully qualified ID of the tenant. For example, /tenants/8d65815f-a5b6-402f-9298-045155da7d74. - [WirePath("id")] - public string Id { get; } - /// The tenant ID. For example, 8d65815f-a5b6-402f-9298-045155da7d74. - [WirePath("tenantId")] - public Guid? TenantId { get; } - /// Category of the tenant. - [WirePath("tenantCategory")] - public TenantCategory? TenantCategory { get; } - /// Country/region name of the address for the tenant. - [WirePath("country")] - public string Country { get; } - /// Country/region abbreviation for the tenant. - [WirePath("countryCode")] - public string CountryCode { get; } - /// The display name of the tenant. - [WirePath("displayName")] - public string DisplayName { get; } - /// The list of domains for the tenant. - [WirePath("domains")] - public IReadOnlyList Domains { get; } - /// The default domain for the tenant. - [WirePath("defaultDomain")] - public string DefaultDomain { get; } - /// The tenant type. Only available for 'Home' tenant category. - [WirePath("tenantType")] - public string TenantType { get; } - /// The tenant's branding logo URL. Only available for 'Home' tenant category. - [WirePath("tenantBrandingLogoUrl")] - public Uri TenantBrandingLogoUri { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionCollection.cs deleted file mode 100644 index bd817fab6a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionCollection.cs +++ /dev/null @@ -1,398 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetTenantPolicyDefinitions method from an instance of . - /// - public partial class TenantPolicyDefinitionCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics; - private readonly PolicyDefinitionsRestOperations _tenantPolicyDefinitionPolicyDefinitionsRestClient; - - /// Initializes a new instance of the class for mocking. - protected TenantPolicyDefinitionCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal TenantPolicyDefinitionCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", TenantPolicyDefinitionResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(TenantPolicyDefinitionResource.ResourceType, out string tenantPolicyDefinitionPolicyDefinitionsApiVersion); - _tenantPolicyDefinitionPolicyDefinitionsRestClient = new PolicyDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, tenantPolicyDefinitionPolicyDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != TenantResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, TenantResource.ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the built-in policy definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("TenantPolicyDefinitionCollection.Get"); - scope.Start(); - try - { - var response = await _tenantPolicyDefinitionPolicyDefinitionsRestClient.GetBuiltInAsync(policyDefinitionName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TenantPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the built-in policy definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("TenantPolicyDefinitionCollection.Get"); - scope.Start(); - try - { - var response = _tenantPolicyDefinitionPolicyDefinitionsRestClient.GetBuiltIn(policyDefinitionName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TenantPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a list of all the built-in policy definitions that match the optional given $filter. If $filter='policyType -eq {value}' is provided, the returned list only includes all built-in policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy definitions whose category match the {value}. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions - /// - /// - /// Operation Id - /// PolicyDefinitions_ListBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _tenantPolicyDefinitionPolicyDefinitionsRestClient.CreateListBuiltInRequest(filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _tenantPolicyDefinitionPolicyDefinitionsRestClient.CreateListBuiltInNextPageRequest(nextLink, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new TenantPolicyDefinitionResource(Client, PolicyDefinitionData.DeserializePolicyDefinitionData(e)), _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics, Pipeline, "TenantPolicyDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// This operation retrieves a list of all the built-in policy definitions that match the optional given $filter. If $filter='policyType -eq {value}' is provided, the returned list only includes all built-in policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy definitions whose category match the {value}. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions - /// - /// - /// Operation Id - /// PolicyDefinitions_ListBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _tenantPolicyDefinitionPolicyDefinitionsRestClient.CreateListBuiltInRequest(filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _tenantPolicyDefinitionPolicyDefinitionsRestClient.CreateListBuiltInNextPageRequest(nextLink, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new TenantPolicyDefinitionResource(Client, PolicyDefinitionData.DeserializePolicyDefinitionData(e)), _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics, Pipeline, "TenantPolicyDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("TenantPolicyDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = await _tenantPolicyDefinitionPolicyDefinitionsRestClient.GetBuiltInAsync(policyDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("TenantPolicyDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = _tenantPolicyDefinitionPolicyDefinitionsRestClient.GetBuiltIn(policyDefinitionName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("TenantPolicyDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _tenantPolicyDefinitionPolicyDefinitionsRestClient.GetBuiltInAsync(policyDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new TenantPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("TenantPolicyDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = _tenantPolicyDefinitionPolicyDefinitionsRestClient.GetBuiltIn(policyDefinitionName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new TenantPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionResource.Serialization.cs deleted file mode 100644 index 6d08620cc8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class TenantPolicyDefinitionResource : IJsonModel - { - private static PolicyDefinitionData s_dataDeserializationInstance; - private static PolicyDefinitionData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - PolicyDefinitionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - PolicyDefinitionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionResource.cs deleted file mode 100644 index a8464ce670..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionResource.cs +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a TenantPolicyDefinition along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetTenantPolicyDefinitionResource method. - /// Otherwise you can get one from its parent resource using the GetTenantPolicyDefinition method. - /// - public partial class TenantPolicyDefinitionResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The policyDefinitionName. - public static ResourceIdentifier CreateResourceIdentifier(string policyDefinitionName) - { - var resourceId = $"/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics; - private readonly PolicyDefinitionsRestOperations _tenantPolicyDefinitionPolicyDefinitionsRestClient; - private readonly PolicyDefinitionData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Authorization/policyDefinitions"; - - /// Initializes a new instance of the class for mocking. - protected TenantPolicyDefinitionResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal TenantPolicyDefinitionResource(ArmClient client, PolicyDefinitionData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal TenantPolicyDefinitionResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string tenantPolicyDefinitionPolicyDefinitionsApiVersion); - _tenantPolicyDefinitionPolicyDefinitionsRestClient = new PolicyDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, tenantPolicyDefinitionPolicyDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual PolicyDefinitionData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the built-in policy definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("TenantPolicyDefinitionResource.Get"); - scope.Start(); - try - { - var response = await _tenantPolicyDefinitionPolicyDefinitionsRestClient.GetBuiltInAsync(Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TenantPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the built-in policy definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("TenantPolicyDefinitionResource.Get"); - scope.Start(); - try - { - var response = _tenantPolicyDefinitionPolicyDefinitionsRestClient.GetBuiltIn(Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TenantPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionCollection.cs deleted file mode 100644 index dbc7feb42d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionCollection.cs +++ /dev/null @@ -1,398 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetTenantPolicySetDefinitions method from an instance of . - /// - public partial class TenantPolicySetDefinitionCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics; - private readonly PolicySetDefinitionsRestOperations _tenantPolicySetDefinitionPolicySetDefinitionsRestClient; - - /// Initializes a new instance of the class for mocking. - protected TenantPolicySetDefinitionCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal TenantPolicySetDefinitionCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", TenantPolicySetDefinitionResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(TenantPolicySetDefinitionResource.ResourceType, out string tenantPolicySetDefinitionPolicySetDefinitionsApiVersion); - _tenantPolicySetDefinitionPolicySetDefinitionsRestClient = new PolicySetDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, tenantPolicySetDefinitionPolicySetDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != TenantResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, TenantResource.ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the built-in policy set definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.Get"); - scope.Start(); - try - { - var response = await _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltInAsync(policySetDefinitionName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TenantPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the built-in policy set definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.Get"); - scope.Start(); - try - { - var response = _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltIn(policySetDefinitionName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TenantPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a list of all the built-in policy set definitions that match the optional given $filter. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy set definitions whose category match the {value}. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions - /// - /// - /// Operation Id - /// PolicySetDefinitions_ListBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListBuiltInRequest(filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListBuiltInNextPageRequest(nextLink, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new TenantPolicySetDefinitionResource(Client, PolicySetDefinitionData.DeserializePolicySetDefinitionData(e)), _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics, Pipeline, "TenantPolicySetDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// This operation retrieves a list of all the built-in policy set definitions that match the optional given $filter. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy set definitions whose category match the {value}. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions - /// - /// - /// Operation Id - /// PolicySetDefinitions_ListBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListBuiltInRequest(filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListBuiltInNextPageRequest(nextLink, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new TenantPolicySetDefinitionResource(Client, PolicySetDefinitionData.DeserializePolicySetDefinitionData(e)), _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics, Pipeline, "TenantPolicySetDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = await _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltInAsync(policySetDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltIn(policySetDefinitionName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltInAsync(policySetDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new TenantPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltIn(policySetDefinitionName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new TenantPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionResource.Serialization.cs deleted file mode 100644 index e2e25a534c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class TenantPolicySetDefinitionResource : IJsonModel - { - private static PolicySetDefinitionData s_dataDeserializationInstance; - private static PolicySetDefinitionData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - PolicySetDefinitionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - PolicySetDefinitionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionResource.cs deleted file mode 100644 index ca45c6dc6a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionResource.cs +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a TenantPolicySetDefinition along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetTenantPolicySetDefinitionResource method. - /// Otherwise you can get one from its parent resource using the GetTenantPolicySetDefinition method. - /// - public partial class TenantPolicySetDefinitionResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The policySetDefinitionName. - public static ResourceIdentifier CreateResourceIdentifier(string policySetDefinitionName) - { - var resourceId = $"/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics; - private readonly PolicySetDefinitionsRestOperations _tenantPolicySetDefinitionPolicySetDefinitionsRestClient; - private readonly PolicySetDefinitionData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Authorization/policySetDefinitions"; - - /// Initializes a new instance of the class for mocking. - protected TenantPolicySetDefinitionResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal TenantPolicySetDefinitionResource(ArmClient client, PolicySetDefinitionData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal TenantPolicySetDefinitionResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string tenantPolicySetDefinitionPolicySetDefinitionsApiVersion); - _tenantPolicySetDefinitionPolicySetDefinitionsRestClient = new PolicySetDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, tenantPolicySetDefinitionPolicySetDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual PolicySetDefinitionData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the built-in policy set definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionResource.Get"); - scope.Start(); - try - { - var response = await _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltInAsync(Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TenantPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the built-in policy set definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionResource.Get"); - scope.Start(); - try - { - var response = _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltIn(Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TenantPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantResource.Serialization.cs deleted file mode 100644 index 7b9b360a83..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class TenantResource : IJsonModel - { - private static TenantData s_dataDeserializationInstance; - private static TenantData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - TenantData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - TenantData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantResource.cs deleted file mode 100644 index 1b1536a286..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Resources/Generated/TenantResource.cs +++ /dev/null @@ -1,505 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a Tenant along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetTenantResource method. - /// - public partial class TenantResource : ArmResource - { - private readonly ClientDiagnostics _tenantClientDiagnostics; - private readonly TenantsRestOperations _tenantRestClient; - private readonly ClientDiagnostics _resourceProviderProvidersClientDiagnostics; - private readonly ProvidersRestOperations _resourceProviderProvidersRestClient; - private readonly ClientDiagnostics _providersClientDiagnostics; - private readonly ProvidersRestOperations _providersRestClient; - private readonly TenantData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Resources/tenants"; - - /// Initializes a new instance of the class for mocking. - protected TenantResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal TenantResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _tenantClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string tenantApiVersion); - _tenantRestClient = new TenantsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, tenantApiVersion); - _resourceProviderProvidersClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceProviderResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceProviderResource.ResourceType, out string resourceProviderProvidersApiVersion); - _resourceProviderProvidersRestClient = new ProvidersRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, resourceProviderProvidersApiVersion); - _providersClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ProviderConstants.DefaultProviderNamespace, Diagnostics); - _providersRestClient = new ProvidersRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual TenantData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// Gets a collection of TenantPolicyDefinitionResources in the Tenant. - /// An object representing collection of TenantPolicyDefinitionResources and their operations over a TenantPolicyDefinitionResource. - public virtual TenantPolicyDefinitionCollection GetTenantPolicyDefinitions() - { - return GetCachedClient(client => new TenantPolicyDefinitionCollection(client, Id)); - } - - /// - /// This operation retrieves the built-in policy definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetTenantPolicyDefinitionAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - return await GetTenantPolicyDefinitions().GetAsync(policyDefinitionName, cancellationToken).ConfigureAwait(false); - } - - /// - /// This operation retrieves the built-in policy definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetTenantPolicyDefinition(string policyDefinitionName, CancellationToken cancellationToken = default) - { - return GetTenantPolicyDefinitions().Get(policyDefinitionName, cancellationToken); - } - - /// Gets a collection of TenantPolicySetDefinitionResources in the Tenant. - /// An object representing collection of TenantPolicySetDefinitionResources and their operations over a TenantPolicySetDefinitionResource. - public virtual TenantPolicySetDefinitionCollection GetTenantPolicySetDefinitions() - { - return GetCachedClient(client => new TenantPolicySetDefinitionCollection(client, Id)); - } - - /// - /// This operation retrieves the built-in policy set definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetTenantPolicySetDefinitionAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - return await GetTenantPolicySetDefinitions().GetAsync(policySetDefinitionName, cancellationToken).ConfigureAwait(false); - } - - /// - /// This operation retrieves the built-in policy set definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetTenantPolicySetDefinition(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - return GetTenantPolicySetDefinitions().Get(policySetDefinitionName, cancellationToken); - } - - /// Gets a collection of DataPolicyManifestResources in the Tenant. - /// An object representing collection of DataPolicyManifestResources and their operations over a DataPolicyManifestResource. - public virtual DataPolicyManifestCollection GetDataPolicyManifests() - { - return GetCachedClient(client => new DataPolicyManifestCollection(client, Id)); - } - - /// - /// This operation retrieves the data policy manifest with the given policy mode. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetDataPolicyManifestAsync(string policyMode, CancellationToken cancellationToken = default) - { - return await GetDataPolicyManifests().GetAsync(policyMode, cancellationToken).ConfigureAwait(false); - } - - /// - /// This operation retrieves the data policy manifest with the given policy mode. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetDataPolicyManifest(string policyMode, CancellationToken cancellationToken = default) - { - return GetDataPolicyManifests().Get(policyMode, cancellationToken); - } - - /// Gets a collection of GenericResources in the Tenant. - /// An object representing collection of GenericResources and their operations over a GenericResource. - public virtual GenericResourceCollection GetGenericResources() - { - return GetCachedClient(client => new GenericResourceCollection(client, Id)); - } - - /// Gets a collection of SubscriptionResources in the Tenant. - /// An object representing collection of SubscriptionResources and their operations over a SubscriptionResource. - public virtual SubscriptionCollection GetSubscriptions() - { - return GetCachedClient(client => new SubscriptionCollection(client, Id)); - } - - /// - /// Gets details about a specified subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The ID of the target subscription. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetSubscriptionAsync(string subscriptionId, CancellationToken cancellationToken = default) - { - return await GetSubscriptions().GetAsync(subscriptionId, cancellationToken).ConfigureAwait(false); - } - - /// - /// Gets details about a specified subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The ID of the target subscription. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetSubscription(string subscriptionId, CancellationToken cancellationToken = default) - { - return GetSubscriptions().Get(subscriptionId, cancellationToken); - } - - /// - /// Gets all resource providers for the tenant. - /// - /// - /// Request Path - /// /providers - /// - /// - /// Operation Id - /// Providers_ListAtTenantScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetTenantResourceProvidersAsync(string expand = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _resourceProviderProvidersRestClient.CreateListAtTenantScopeRequest(expand); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _resourceProviderProvidersRestClient.CreateListAtTenantScopeNextPageRequest(nextLink, expand); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => TenantResourceProvider.DeserializeTenantResourceProvider(e), _resourceProviderProvidersClientDiagnostics, Pipeline, "TenantResource.GetTenantResourceProviders", "value", "nextLink", cancellationToken); - } - - /// - /// Gets all resource providers for the tenant. - /// - /// - /// Request Path - /// /providers - /// - /// - /// Operation Id - /// Providers_ListAtTenantScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetTenantResourceProviders(string expand = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _resourceProviderProvidersRestClient.CreateListAtTenantScopeRequest(expand); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _resourceProviderProvidersRestClient.CreateListAtTenantScopeNextPageRequest(nextLink, expand); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => TenantResourceProvider.DeserializeTenantResourceProvider(e), _resourceProviderProvidersClientDiagnostics, Pipeline, "TenantResource.GetTenantResourceProviders", "value", "nextLink", cancellationToken); - } - - /// - /// Gets the specified resource provider at the tenant level. - /// - /// - /// Request Path - /// /providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_GetAtTenantScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetTenantResourceProviderAsync(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var scope = _providersClientDiagnostics.CreateScope("TenantResource.GetTenantResourceProvider"); - scope.Start(); - try - { - var response = await _providersRestClient.GetAtTenantScopeAsync(resourceProviderNamespace, expand, cancellationToken).ConfigureAwait(false); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets the specified resource provider at the tenant level. - /// - /// - /// Request Path - /// /providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_GetAtTenantScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response GetTenantResourceProvider(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var scope = _providersClientDiagnostics.CreateScope("TenantResource.GetTenantResourceProvider"); - scope.Start(); - try - { - var response = _providersRestClient.GetAtTenantScope(resourceProviderNamespace, expand, cancellationToken); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/AppContextSwitchHelper.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/AppContextSwitchHelper.cs deleted file mode 100644 index 6b511aae6c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/AppContextSwitchHelper.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -#nullable enable - -namespace Azure.Core -{ - /// - /// Helper for interacting with AppConfig settings and their related Environment variable settings. - /// - internal static class AppContextSwitchHelper - { - /// - /// Determines if either an AppContext switch or its corresponding Environment Variable is set - /// - /// Name of the AppContext switch. - /// Name of the Environment variable. - /// If the AppContext switch has been set, returns the value of the switch. - /// If the AppContext switch has not been set, returns the value of the environment variable. - /// False if neither is set. - /// - public static bool GetConfigValue(string appContexSwitchName, string environmentVariableName) - { - // First check for the AppContext switch, giving it priority over the environment variable. - if (AppContext.TryGetSwitch(appContexSwitchName, out bool value)) - { - return value; - } - // AppContext switch wasn't used. Check the environment variable. - string? envVar = Environment.GetEnvironmentVariable(environmentVariableName); - if (envVar != null && (envVar.Equals("true", StringComparison.OrdinalIgnoreCase) || envVar.Equals("1"))) - { - return true; - } - - // Default to false. - return false; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/AsyncLockWithValue.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/AsyncLockWithValue.cs deleted file mode 100644 index 96aa1a559c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/AsyncLockWithValue.cs +++ /dev/null @@ -1,260 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; - -namespace Azure.Core -{ - /// - /// Primitive that combines async lock and value cache - /// - /// - internal sealed class AsyncLockWithValue - { - private readonly object _syncObj = new(); - private Queue>? _waiters; - private bool _isLocked; - private bool _hasValue; - private long _index; - private T? _value; - - public bool HasValue - { - get - { - lock (_syncObj) - { - return _hasValue; - } - } - } - - public AsyncLockWithValue() { } - - public AsyncLockWithValue(T value) - { - _hasValue = true; - _value = value; - } - - public bool TryGetValue(out T? value) - { - lock (_syncObj) - { - if (_hasValue) - { - value = _value; - return true; - } - } - - value = default; - return false; - } - - /// - /// Method that either returns cached value or acquire a lock. - /// If one caller has acquired a lock, other callers will be waiting for the lock to be released. - /// If value is set, lock is released and all waiters get that value. - /// If value isn't set, the next waiter in the queue will get the lock. - /// - /// - /// - /// - public async ValueTask GetLockOrValueAsync(bool async, CancellationToken cancellationToken = default) - { - TaskCompletionSource valueTcs; - lock (_syncObj) - { - // If there is a value, just return it - if (_hasValue) - { - return new LockOrValue(_value!); - } - - // If lock isn't acquire yet, acquire it and return to the caller - if (!_isLocked) - { - _isLocked = true; - _index = unchecked(_index + 1); - return new LockOrValue(this, _index); - } - - // Check cancellationToken before instantiating waiter - cancellationToken.ThrowIfCancellationRequested(); - - // If lock is already taken, create a waiter and wait either until value is set or lock can be acquired by this waiter - _waiters ??= new Queue>(); - // if async == false, valueTcs will be waited only in this thread and only synchronously, so RunContinuationsAsynchronously isn't needed. - valueTcs = new TaskCompletionSource(async ? TaskCreationOptions.RunContinuationsAsynchronously : TaskCreationOptions.None); - _waiters.Enqueue(valueTcs); - } - - try - { - if (async) - { - return await valueTcs.Task.AwaitWithCancellation(cancellationToken); - } - -#pragma warning disable AZC0104 // Use EnsureCompleted() directly on asynchronous method return value. -#pragma warning disable AZC0111 // DO NOT use EnsureCompleted in possibly asynchronous scope. - valueTcs.Task.Wait(cancellationToken); - return valueTcs.Task.EnsureCompleted(); -#pragma warning restore AZC0111 // DO NOT use EnsureCompleted in possibly asynchronous scope. -#pragma warning restore AZC0104 // Use EnsureCompleted() directly on asynchronous method return value. - } - catch (OperationCanceledException) - { - // Throw OperationCanceledException only if another thread hasn't set a value to this waiter - // by calling either Reset or SetValue - if (valueTcs.TrySetCanceled(cancellationToken)) - { - throw; - } - - return valueTcs.Task.Result; - } - } - - /// - /// Set value to the cache and to all the waiters - /// - /// - /// - private void SetValue(T value, in long lockIndex) - { - Queue> waiters; - lock (_syncObj) - { - if (lockIndex != _index) - { - throw new InvalidOperationException($"Disposed {nameof(LockOrValue)} tries to set value. Current index: {_index}, {nameof(LockOrValue)} index: {lockIndex}"); - } - - _value = value; - _hasValue = true; - _index = 0; - _isLocked = false; - if (_waiters == default) - { - return; - } - - waiters = _waiters; - _waiters = default; - } - - while (waiters.Count > 0) - { - waiters.Dequeue().TrySetResult(new LockOrValue(value)); - } - } - - /// - /// Release the lock and allow next waiter acquire it - /// - private void Reset(in long lockIndex) - { - UnlockOrGetNextWaiter(lockIndex, out var nextWaiter); - while (nextWaiter != default && !nextWaiter.TrySetResult(new LockOrValue(this, unchecked(lockIndex + 1)))) - { - UnlockOrGetNextWaiter(lockIndex, out nextWaiter); - } - } - - private void UnlockOrGetNextWaiter(in long lockIndex, out TaskCompletionSource? nextWaiter) - { - lock (_syncObj) - { - nextWaiter = default; - // If lock isn't acquired, just return - if (!_isLocked || lockIndex != _index) - { - return; - } - - _index = unchecked(lockIndex + 1); - - // If lock was acquired, but there are no waiters, unlock and return - if (_waiters == default) - { - _isLocked = false; - return; - } - - // Find the next waiter - while (_waiters.Count > 0) - { - nextWaiter = _waiters.Dequeue(); - if (!nextWaiter.Task.IsCompleted) - { - // Return the waiter only if it wasn't canceled already - return; - } - } - - // If no next waiter has been found, unlock and return - _isLocked = false; - } - } - - public readonly struct LockOrValue : IDisposable - { - private readonly AsyncLockWithValue? _owner; - private readonly T? _value; - private readonly long _index; - - /// - /// Returns true if lock contains the cached value. Otherwise false. - /// - public bool HasValue => _owner == default; - - /// - /// Returns cached value if it was set when lock has been created. Throws exception otherwise. - /// - /// Value isn't set. - public T Value => HasValue ? _value! : throw new InvalidOperationException("Value isn't set"); - - public LockOrValue(T value) - { - _owner = default; - _value = value; - _index = 0; - } - - public LockOrValue(AsyncLockWithValue owner, long index) - { - _owner = owner; - _index = index; - _value = default; - } - - /// - /// Set value to the cache and to all the waiters. - /// - /// - /// Value is set already. - public void SetValue(T value) - { - if (_owner != null) - { - _owner.SetValue(value, _index); - } - else - { - throw new InvalidOperationException("Value for the lock is set already"); - } - } - - public void Dispose() => _owner?.Reset(_index); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/AzureResourceProviderNamespaceAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/AzureResourceProviderNamespaceAttribute.cs deleted file mode 100644 index e9ac665a94..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/AzureResourceProviderNamespaceAttribute.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -namespace Azure.Core -{ - /// - /// This attribute should be set on all client assemblies with value of one of the resource providers - /// from the https://docs.microsoft.com/azure/azure-resource-manager/management/azure-services-resource-providers list. - /// - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] - internal class AzureResourceProviderNamespaceAttribute : Attribute - { - public string ResourceProviderNamespace { get; } - - public AzureResourceProviderNamespaceAttribute(string resourceProviderNamespace) - { - ResourceProviderNamespace = resourceProviderNamespace; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ClientDiagnostics.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ClientDiagnostics.cs deleted file mode 100644 index f9fc345937..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ClientDiagnostics.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; - -#nullable enable - -namespace Azure.Core.Pipeline -{ - internal class ClientDiagnostics : DiagnosticScopeFactory - { - /// - /// Initializes a new instance of the class. - /// - /// The customer provided client options object. - /// Flag controlling if - /// created by this for client method calls should be suppressed when called - /// by other Azure SDK client methods. It's recommended to set it to true for new clients; use default (null) - /// for backward compatibility reasons, or set it to false to explicitly disable suppression for specific cases. - /// The default value could change in the future, the flag should be only set to false if suppression for the client - /// should never be enabled. - public ClientDiagnostics(ClientOptions options, bool? suppressNestedClientActivities = null) - : this(options.GetType().Namespace!, - GetResourceProviderNamespace(options.GetType().Assembly), - options.Diagnostics, - suppressNestedClientActivities) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// Namespace of the client class, such as Azure.Storage or Azure.AppConfiguration. - /// Azure Resource Provider namespace of the Azure service SDK is primarily used for. - /// The customer provided client diagnostics options. - /// Flag controlling if - /// created by this for client method calls should be suppressed when called - /// by other Azure SDK client methods. It's recommended to set it to true for new clients, use default (null) for old clients - /// for backward compatibility reasons, or set it to false to explicitly disable suppression for specific cases. - /// The default value could change in the future, the flag should be only set to false if suppression for the client - /// should never be enabled. - public ClientDiagnostics(string optionsNamespace, string? providerNamespace, DiagnosticsOptions diagnosticsOptions, bool? suppressNestedClientActivities = null) - : base(optionsNamespace, providerNamespace, diagnosticsOptions.IsDistributedTracingEnabled, suppressNestedClientActivities.GetValueOrDefault(true), true) - { - } - - internal static HttpMessageSanitizer CreateMessageSanitizer(DiagnosticsOptions diagnostics) - { - return new HttpMessageSanitizer( - diagnostics.LoggedQueryParameters.ToArray(), - diagnostics.LoggedHeaderNames.ToArray()); - } - - internal static string? GetResourceProviderNamespace(Assembly assembly) - { - foreach (var customAttribute in assembly.GetCustomAttributesData()) - { - // Weak bind internal shared type - Type attributeType = customAttribute.AttributeType!; - if (attributeType.FullName == ("Azure.Core.AzureResourceProviderNamespaceAttribute")) - { - IList namedArguments = customAttribute.ConstructorArguments; - return namedArguments.Single().Value as string; - } - } - - return null; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/DiagnosticScope.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/DiagnosticScope.cs deleted file mode 100644 index c32bf2b8cb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/DiagnosticScope.cs +++ /dev/null @@ -1,448 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.Linq.Expressions; -using System.Net.Http; -using System.Reflection; - -namespace Azure.Core.Pipeline -{ - internal readonly struct DiagnosticScope : IDisposable - { - private const string AzureSdkScopeLabel = "az.sdk.scope"; - internal const string OpenTelemetrySchemaAttribute = "az.schema_url"; - - // we follow OpenTelemtery Semantic Conventions 1.23.0 - // https://github.com/open-telemetry/semantic-conventions/blob/v1.23.0 - internal const string OpenTelemetrySchemaVersion = "https://opentelemetry.io/schemas/1.23.0"; - private static readonly object AzureSdkScopeValue = bool.TrueString; - private readonly ActivityAdapter? _activityAdapter; - private readonly bool _suppressNestedClientActivities; - - internal DiagnosticScope(string scopeName, DiagnosticListener source, object? diagnosticSourceArgs, ActivitySource? activitySource, System.Diagnostics.ActivityKind kind, bool suppressNestedClientActivities) - { - // ActivityKind.Internal and Client both can represent public API calls depending on the SDK - _suppressNestedClientActivities = (kind == ActivityKind.Client || kind == System.Diagnostics.ActivityKind.Internal) ? suppressNestedClientActivities : false; - - // outer scope presence is enough to suppress any inner scope, regardless of inner scope configuation. - bool hasListeners; - hasListeners = activitySource?.HasListeners() ?? false; - IsEnabled = source.IsEnabled() || hasListeners; - - if (_suppressNestedClientActivities) - { - IsEnabled &= !AzureSdkScopeValue.Equals(Activity.Current?.GetCustomProperty(AzureSdkScopeLabel)); - } - - _activityAdapter = IsEnabled ? new ActivityAdapter( - activitySource: activitySource, - diagnosticSource: source, - activityName: scopeName, - kind: kind, - diagnosticSourceArgs: diagnosticSourceArgs) : null; - } - - public bool IsEnabled { get; } - - public void AddAttribute(string name, string? value) - { - if (value != null) - { - _activityAdapter?.AddTag(name, value); - } - } - - public void AddIntegerAttribute(string name, int value) - { - _activityAdapter?.AddTag(name, value); - } - - public void AddLongAttribute(string name, long value) - { - _activityAdapter?.AddTag(name, value); - } - - public void AddAttribute(string name, T value, Func format) - { - if (_activityAdapter != null && value != null) - { - var formattedValue = format(value); - _activityAdapter.AddTag(name, formattedValue); - } - } - - /// - /// Adds a link to the scope. This must be called before has been called for the DiagnosticScope. - /// - /// The traceparent for the link. - /// The tracestate for the link. - /// Optional attributes to associate with the link. - public void AddLink(string traceparent, string? tracestate, IDictionary? attributes = null) - { - _activityAdapter?.AddLink(traceparent, tracestate, attributes); - } - - public void Start() - { - Activity? started = _activityAdapter?.Start(); - if (_suppressNestedClientActivities) - { - started?.SetCustomProperty(AzureSdkScopeLabel, AzureSdkScopeValue); - } - } - - public void SetDisplayName(string displayName) - { - _activityAdapter?.SetDisplayName(displayName); - } - - public void SetStartTime(DateTime dateTime) - { - _activityAdapter?.SetStartTime(dateTime); - } - - /// - /// Sets the trace context for the current scope. - /// - /// The trace parent to set for the current scope. - /// The trace state to set for the current scope. - public void SetTraceContext(string traceparent, string? tracestate = default) - { - _activityAdapter?.SetTraceContext(traceparent, tracestate); - } - - public void Dispose() - { - // Reverse the Start order - _activityAdapter?.Dispose(); - } - - /// - /// Marks the scope as failed. - /// - /// The exception to associate with the failed scope. - public void Failed(Exception exception) - { - if (exception is RequestFailedException requestFailedException) - { - // TODO (limolkova) when we start targeting .NET 8 we should put - // requestFailedException.InnerException.HttpRequestError into error.type - - string? errorCode = string.IsNullOrEmpty(requestFailedException.ErrorCode) ? null : requestFailedException.ErrorCode; - _activityAdapter?.MarkFailed(exception, errorCode); - } - else - { - _activityAdapter?.MarkFailed(exception, null); - } - } - - /// - /// Marks the scope as failed with low-cardinality error.type attribute. - /// - /// Error code to associate with the failed scope. - public void Failed(string errorCode) - { - _activityAdapter?.MarkFailed((Exception?)null, errorCode); - } - - private class DiagnosticActivity : Activity - { -#pragma warning disable 109 // extra new modifier - public new IEnumerable Links { get; set; } = Array.Empty(); -#pragma warning restore 109 - - public DiagnosticActivity(string operationName) : base(operationName) - { - } - } - - private class ActivityAdapter : IDisposable - { - private readonly ActivitySource? _activitySource; - private readonly DiagnosticSource _diagnosticSource; - private readonly string _activityName; - private readonly System.Diagnostics.ActivityKind _kind; - private readonly object? _diagnosticSourceArgs; - - private Activity? _currentActivity; - private Activity? _sampleOutActivity; - - private ActivityTagsCollection? _tagCollection; - private DateTimeOffset _startTime; - private List? _links; - private string? _traceparent; - private string? _tracestate; - private string? _displayName; - - public ActivityAdapter(ActivitySource? activitySource, DiagnosticSource diagnosticSource, string activityName, System.Diagnostics.ActivityKind kind, object? diagnosticSourceArgs) - { - _activitySource = activitySource; - _diagnosticSource = diagnosticSource; - _activityName = activityName; - _kind = kind; - _diagnosticSourceArgs = diagnosticSourceArgs; - } - - public void AddTag(string name, object value) - { - if (_sampleOutActivity == null) - { - if (_currentActivity == null) - { - // Activity is not started yet, add the value to the collection - // that is going to be passed to StartActivity - _tagCollection ??= new ActivityTagsCollection(); - _tagCollection[name] = value!; - } - else - { - AddObjectTag(name, value); - } - } - } - - private IReadOnlyList GetDiagnosticSourceLinkCollection() - { - if (_links == null) - { - return Array.Empty(); - } - - var linkCollection = new List(); - - foreach (var link in _links) - { - var activity = new Activity("LinkedActivity"); - activity.SetIdFormat(ActivityIdFormat.W3C); - if (link.Context != default) - { - activity.SetParentId(ActivityContextToTraceParent(link.Context)); - activity.TraceStateString = link.Context.TraceState; - } - - if (link.Tags != null) - { - foreach (var tag in link.Tags) - { - if (tag.Value != null) - { - // old code path, only string attributes are supported - activity.AddTag(tag.Key, tag.Value.ToString()); - } - } - } - linkCollection.Add(activity); - } - - return linkCollection; - } - - private static string ActivityContextToTraceParent(ActivityContext context) - { - string flags = (context.TraceFlags == ActivityTraceFlags.None) ? "00" : "01"; - return "00-" + context.TraceId + "-" + context.SpanId + "-" + flags; - } - - public void AddLink(string traceparent, string? tracestate, IDictionary? attributes) - { - // if context is invalid, we should still add a link since it contains attributes - // so we let ActivityLink deal with the default context. - // This is otel spec requirement and default context is allowed on links. - ActivityContext.TryParse(traceparent, tracestate, out var context); - var linkedActivity = new ActivityLink(context, attributes == null ? null : new ActivityTagsCollection(attributes)); - _links ??= new List(); - _links.Add(linkedActivity); - } - - public Activity? Start() - { - _currentActivity = StartActivitySourceActivity(); - if (_currentActivity != null) - { - if (!_currentActivity.IsAllDataRequested) - { - _sampleOutActivity = _currentActivity; - _currentActivity = null; - - return null; - } - - _currentActivity.SetTag(OpenTelemetrySchemaAttribute, OpenTelemetrySchemaVersion); - } - else - { - if (!_diagnosticSource.IsEnabled(_activityName, _diagnosticSourceArgs)) - { - return null; - } - - switch (_kind) - { - case ActivityKind.Internal: - AddTag("kind", "internal"); - break; - case ActivityKind.Server: - AddTag("kind", "server"); - break; - case ActivityKind.Client: - AddTag("kind", "client"); - break; - case ActivityKind.Producer: - AddTag("kind", "producer"); - break; - case ActivityKind.Consumer: - AddTag("kind", "consumer"); - break; - } - - _currentActivity = new DiagnosticActivity(_activityName) - { - Links = GetDiagnosticSourceLinkCollection(), - }; - _currentActivity.SetIdFormat(ActivityIdFormat.W3C); - - if (_startTime != default) - { - _currentActivity.SetStartTime(_startTime.UtcDateTime); - } - - if (_tagCollection != null) - { - foreach (var tag in _tagCollection) - { - AddObjectTag(tag.Key, tag.Value!); - } - } - - if (_traceparent != null) - { - _currentActivity.SetParentId(_traceparent); - } - - if (_tracestate != null) - { - _currentActivity.TraceStateString = _tracestate; - } - - _currentActivity.Start(); - } - - if (_displayName != null) - { - _currentActivity.DisplayName = _displayName; - } - - return _currentActivity; - } - - public void SetDisplayName(string displayName) - { - _displayName = displayName; - if (_currentActivity != null) - { - _currentActivity.DisplayName = _displayName; - } - } - - private Activity? StartActivitySourceActivity() - { - if (_activitySource == null) - { - return null; - } - // TODO(limolkova) set isRemote to true once we switch to DiagnosticSource 7.0 - ActivityContext.TryParse(_traceparent, _tracestate, out ActivityContext context); - return _activitySource.StartActivity(_activityName, _kind, context, _tagCollection, _links, _startTime); - } - - public void SetStartTime(DateTime startTime) - { - _startTime = startTime; - _currentActivity?.SetStartTime(startTime); - } - - public void MarkFailed(T? exception, string? errorCode) - { - if (errorCode == null && exception != null) - { - errorCode = exception.GetType().FullName; - } - - errorCode ??= "_OTHER"; - - // SetStatus is only defined in NET 6 or greater - _currentActivity?.SetTag("error.type", errorCode); - _currentActivity?.SetStatus(ActivityStatusCode.Error, exception?.ToString()); - } - - public void SetTraceContext(string traceparent, string? tracestate) - { - if (_currentActivity != null) - { - throw new InvalidOperationException("Traceparent can not be set after the activity is started."); - } - _traceparent = traceparent; - _tracestate = tracestate; - } - - private void AddObjectTag(string name, object value) - { - if (_activitySource?.HasListeners() == true) - { - _currentActivity?.SetTag(name, value); - } - else - { - _currentActivity?.AddTag(name, value.ToString()); - } - } - - public void Dispose() - { - var activity = _currentActivity ?? _sampleOutActivity; - if (activity == null) - { - return; - } - - if (activity.Duration == TimeSpan.Zero) - activity.SetEndTime(DateTime.UtcNow); - - activity.Dispose(); - - _currentActivity = null; - _sampleOutActivity = null; - } - } - } - -#pragma warning disable SA1507 // File can not contain multiple types - /// - /// Until Activity Source is no longer considered experimental. - /// - internal static class ActivityExtensions - { - static ActivityExtensions() - { - ResetFeatureSwitch(); - } - - public static bool SupportsActivitySource { get; private set; } - - public static void ResetFeatureSwitch() - { - SupportsActivitySource = AppContextSwitchHelper.GetConfigValue( - "Azure.Experimental.EnableActivitySource", - "AZURE_EXPERIMENTAL_ENABLE_ACTIVITY_SOURCE"); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/DiagnosticScopeFactory.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/DiagnosticScopeFactory.cs deleted file mode 100644 index 5e1d9c556e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/DiagnosticScopeFactory.cs +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Threading; - -#nullable enable - -namespace Azure.Core.Pipeline -{ -#pragma warning disable CA1001 // Types that own disposable fields should be disposable - internal class DiagnosticScopeFactory -#pragma warning restore CA1001 // Types that own disposable fields should be disposable - { - private static Dictionary? _listeners; - private readonly string? _resourceProviderNamespace; - private readonly DiagnosticListener? _source; - private readonly bool _suppressNestedClientActivities; - private readonly bool _isStable; - private static readonly ConcurrentDictionary ActivitySources = new(); - - /// - /// Creates diagnostic scope factory. - /// - /// The namespace which is used as a prefix for all ActivitySources created by the factory and the name of DiagnosticSource (when used). - /// Azure resource provider namespace. - /// Flag indicating if distributed tracing is enabled. - /// Flag indicating if nested Azure SDK activities describing public API calls should be suppressed. - /// Whether instrumentation is considered stable. When false, experimental feature flag controls if tracing is enabled. - public DiagnosticScopeFactory(string clientNamespace, string? resourceProviderNamespace, bool isActivityEnabled, bool suppressNestedClientActivities = true, bool isStable = false) - { - _resourceProviderNamespace = resourceProviderNamespace; - IsActivityEnabled = isActivityEnabled; - _suppressNestedClientActivities = suppressNestedClientActivities; - _isStable = isStable; - - if (IsActivityEnabled) - { - var listeners = LazyInitializer.EnsureInitialized(ref _listeners); - - lock (listeners!) - { - if (!listeners.TryGetValue(clientNamespace, out _source)) - { - _source = new DiagnosticListener(clientNamespace); - listeners[clientNamespace] = _source; - } - } - } - } - - public bool IsActivityEnabled { get; } - - public DiagnosticScope CreateScope(string name, System.Diagnostics.ActivityKind kind = ActivityKind.Internal) - { - if (_source == null) - { - return default; - } - - var scope = new DiagnosticScope( - scopeName: name, - source: _source, - diagnosticSourceArgs: null, - activitySource: GetActivitySource(_source.Name, name), - kind: kind, - suppressNestedClientActivities: _suppressNestedClientActivities); - - if (_resourceProviderNamespace != null) - { - scope.AddAttribute("az.namespace", _resourceProviderNamespace); - } - return scope; - } - - /// - /// This method combines client namespace and operation name into an ActivitySource name and creates the activity source. - /// For example: - /// ns: Azure.Storage.Blobs - /// name: BlobClient.DownloadTo - /// result Azure.Storage.Blobs.BlobClient - /// - private ActivitySource? GetActivitySource(string ns, string name) - { - bool enabled = _isStable; - enabled |= ActivityExtensions.SupportsActivitySource; - - if (!enabled) - { - return null; - } - - int indexOfDot = name.IndexOf(".", StringComparison.OrdinalIgnoreCase); - string clientName = ns + "." + ((indexOfDot < 0) ? name : name.Substring(0, indexOfDot)); - - return ActivitySources.GetOrAdd(clientName, static n => new ActivitySource(n)); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/FixedDelayWithNoJitterStrategy.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/FixedDelayWithNoJitterStrategy.cs deleted file mode 100644 index 1051e56b3f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/FixedDelayWithNoJitterStrategy.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -#nullable enable - -namespace Azure.Core -{ - /// - /// A delay strategy that uses a fixed delay with no jitter applied. This is used by data plane LROs. - /// - internal class FixedDelayWithNoJitterStrategy : DelayStrategy - { - private static readonly TimeSpan DefaultDelay = TimeSpan.FromSeconds(1); - private readonly TimeSpan _delay; - - public FixedDelayWithNoJitterStrategy(TimeSpan? suggestedDelay = default) : base(suggestedDelay.HasValue ? Max(suggestedDelay.Value, DefaultDelay) : DefaultDelay, 0) - { - _delay = suggestedDelay.HasValue ? Max(suggestedDelay.Value, DefaultDelay) : DefaultDelay; - } - - protected override TimeSpan GetNextDelayCore(Response? response, int retryNumber) => - _delay; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ForwardsClientCallsAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ForwardsClientCallsAttribute.cs deleted file mode 100644 index e9e933541b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ForwardsClientCallsAttribute.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -namespace Azure.Core -{ - /// - /// Marks methods that call methods on other client and don't need their diagnostics verified. - /// - [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] - internal class ForwardsClientCallsAttribute : Attribute - { - /// - /// Creates a new instance of . - /// - public ForwardsClientCallsAttribute() - : this(false) - { - } - - /// - /// Creates a new instance of . - /// - /// Sets whether or not diagnostic scope validation should happen. - public ForwardsClientCallsAttribute(bool skipChecks) - { - SkipChecks = skipChecks; - } - - /// - /// Gets whether or not we should validate DiagnosticScope for this API. - /// In the case where there is an internal API that makes the Azure API call and a public API that uses it we need ForwardsClientCalls. - /// If the public API will cache the results then the diagnostic scope will not always be created because an Azure API is not always called. - /// In this case we need to turn off this validation for this API only. - /// - public bool SkipChecks { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/HashCodeBuilder.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/HashCodeBuilder.cs deleted file mode 100644 index a6a76f93f8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/HashCodeBuilder.cs +++ /dev/null @@ -1,387 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Runtime.CompilerServices; - -#nullable enable - -namespace Azure.Core -{ - /// - /// Copied from https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/HashCode.cs. - /// - internal struct HashCodeBuilder - { - private static readonly uint s_seed = GenerateGlobalSeed(); - - private const uint Prime1 = 2654435761U; - private const uint Prime2 = 2246822519U; - private const uint Prime3 = 3266489917U; - private const uint Prime4 = 668265263U; - private const uint Prime5 = 374761393U; - - private uint _v1, _v2, _v3, _v4; - private uint _queue1, _queue2, _queue3; - private uint _length; - - private static uint GenerateGlobalSeed() - { - return (uint)new Random().Next(); - } - - public static int Combine(T1 value1) - { - // Provide a way of diffusing bits from something with a limited - // input hash space. For example, many enums only have a few - // possible hashes, only using the bottom few bits of the code. Some - // collections are built on the assumption that hashes are spread - // over a larger space, so diffusing the bits may help the - // collection work more efficiently. - - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - - uint hash = MixEmptyState(); - hash += 4; - - hash = QueueRound(hash, hc1); - - hash = MixFinal(hash); - return (int)hash; - } - - public static int Combine(T1 value1, T2 value2) - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - - uint hash = MixEmptyState(); - hash += 8; - - hash = QueueRound(hash, hc1); - hash = QueueRound(hash, hc2); - - hash = MixFinal(hash); - return (int)hash; - } - - public static int Combine(T1 value1, T2 value2, T3 value3) - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - - uint hash = MixEmptyState(); - hash += 12; - - hash = QueueRound(hash, hc1); - hash = QueueRound(hash, hc2); - hash = QueueRound(hash, hc3); - - hash = MixFinal(hash); - return (int)hash; - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4) - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - uint hash = MixState(v1, v2, v3, v4); - hash += 16; - - hash = MixFinal(hash); - return (int)hash; - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5) - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - uint hc5 = (uint)(value5?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - uint hash = MixState(v1, v2, v3, v4); - hash += 20; - - hash = QueueRound(hash, hc5); - - hash = MixFinal(hash); - return (int)hash; - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6) - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - uint hc5 = (uint)(value5?.GetHashCode() ?? 0); - uint hc6 = (uint)(value6?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - uint hash = MixState(v1, v2, v3, v4); - hash += 24; - - hash = QueueRound(hash, hc5); - hash = QueueRound(hash, hc6); - - hash = MixFinal(hash); - return (int)hash; - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7) - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - uint hc5 = (uint)(value5?.GetHashCode() ?? 0); - uint hc6 = (uint)(value6?.GetHashCode() ?? 0); - uint hc7 = (uint)(value7?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - uint hash = MixState(v1, v2, v3, v4); - hash += 28; - - hash = QueueRound(hash, hc5); - hash = QueueRound(hash, hc6); - hash = QueueRound(hash, hc7); - - hash = MixFinal(hash); - return (int)hash; - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7, T8 value8) - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - uint hc5 = (uint)(value5?.GetHashCode() ?? 0); - uint hc6 = (uint)(value6?.GetHashCode() ?? 0); - uint hc7 = (uint)(value7?.GetHashCode() ?? 0); - uint hc8 = (uint)(value8?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - v1 = Round(v1, hc5); - v2 = Round(v2, hc6); - v3 = Round(v3, hc7); - v4 = Round(v4, hc8); - - uint hash = MixState(v1, v2, v3, v4); - hash += 32; - - hash = MixFinal(hash); - return (int)hash; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void Initialize(out uint v1, out uint v2, out uint v3, out uint v4) - { - v1 = s_seed + Prime1 + Prime2; - v2 = s_seed + Prime2; - v3 = s_seed; - v4 = s_seed - Prime1; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint Round(uint hash, uint input) - { - return RotateLeft(hash + input * Prime2, 13) * Prime1; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint QueueRound(uint hash, uint queuedValue) - { - return RotateLeft(hash + queuedValue * Prime3, 17) * Prime4; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint MixState(uint v1, uint v2, uint v3, uint v4) - { - return RotateLeft(v1, 1) + RotateLeft(v2, 7) + RotateLeft(v3, 12) + RotateLeft(v4, 18); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static uint RotateLeft(uint value, int offset) - => (value << offset) | (value >> (64 - offset)); - - private static uint MixEmptyState() - { - return s_seed + Prime5; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint MixFinal(uint hash) - { - hash ^= hash >> 15; - hash *= Prime2; - hash ^= hash >> 13; - hash *= Prime3; - hash ^= hash >> 16; - return hash; - } - - public void Add(T value) - { - Add(value?.GetHashCode() ?? 0); - } - - public void Add(T value, IEqualityComparer? comparer) - { - Add(value is null ? 0 : (comparer?.GetHashCode(value) ?? value.GetHashCode())); - } - - private void Add(int value) - { - // The original xxHash works as follows: - // 0. Initialize immediately. We can't do this in a struct (no - // default ctor). - // 1. Accumulate blocks of length 16 (4 uints) into 4 accumulators. - // 2. Accumulate remaining blocks of length 4 (1 uint) into the - // hash. - // 3. Accumulate remaining blocks of length 1 into the hash. - - // There is no need for #3 as this type only accepts ints. _queue1, - // _queue2 and _queue3 are basically a buffer so that when - // ToHashCode is called we can execute #2 correctly. - - // We need to initialize the xxHash32 state (_v1 to _v4) lazily (see - // #0) nd the last place that can be done if you look at the - // original code is just before the first block of 16 bytes is mixed - // in. The xxHash32 state is never used for streams containing fewer - // than 16 bytes. - - // To see what's really going on here, have a look at the Combine - // methods. - - uint val = (uint)value; - - // Storing the value of _length locally shaves of quite a few bytes - // in the resulting machine code. - uint previousLength = _length++; - uint position = previousLength % 4; - - // Switch can't be inlined. - - if (position == 0) - _queue1 = val; - else if (position == 1) - _queue2 = val; - else if (position == 2) - _queue3 = val; - else // position == 3 - { - if (previousLength == 3) - Initialize(out _v1, out _v2, out _v3, out _v4); - - _v1 = Round(_v1, _queue1); - _v2 = Round(_v2, _queue2); - _v3 = Round(_v3, _queue3); - _v4 = Round(_v4, val); - } - } - - public int ToHashCode() - { - // Storing the value of _length locally shaves of quite a few bytes - // in the resulting machine code. - uint length = _length; - - // position refers to the *next* queue position in this method, so - // position == 1 means that _queue1 is populated; _queue2 would have - // been populated on the next call to Add. - uint position = length % 4; - - // If the length is less than 4, _v1 to _v4 don't contain anything - // yet. xxHash32 treats this differently. - - uint hash = length < 4 ? MixEmptyState() : MixState(_v1, _v2, _v3, _v4); - - // _length is incremented once per Add(Int32) and is therefore 4 - // times too small (xxHash length is in bytes, not ints). - - hash += length * 4; - - // Mix what remains in the queue - - // Switch can't be inlined right now, so use as few branches as - // possible by manually excluding impossible scenarios (position > 1 - // is always false if position is not > 0). - if (position > 0) - { - hash = QueueRound(hash, _queue1); - if (position > 1) - { - hash = QueueRound(hash, _queue2); - if (position > 2) - hash = QueueRound(hash, _queue3); - } - } - - hash = MixFinal(hash); - return (int)hash; - } - -#pragma warning disable 0809 - // Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - // Disallowing GetHashCode and Equals is by design - - // * We decided to not override GetHashCode() to produce the hash code - // as this would be weird, both naming-wise as well as from a - // behavioral standpoint (GetHashCode() should return the object's - // hash code, not the one being computed). - - // * Even though ToHashCode() can be called safely multiple times on - // this implementation, it is not part of the contract. If the - // implementation has to change in the future we don't want to worry - // about people who might have incorrectly used this type. - - [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes. Use ToHashCode to retrieve the computed hash code.", error: true)] - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => throw new NotSupportedException(); - - [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes.", error: true)] - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object? obj) => throw new NotSupportedException(); -#pragma warning restore 0809 - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/HttpMessageSanitizer.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/HttpMessageSanitizer.cs deleted file mode 100644 index 36becf22a5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/HttpMessageSanitizer.cs +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -#nullable enable - -using System; -using System.Collections.Generic; -using System.Text; -using System.Linq; - -namespace Azure.Core; - -internal class HttpMessageSanitizer -{ - private const string LogAllValue = "*"; - private readonly bool _logAllHeaders; - private readonly bool _logFullQueries; - private readonly string[] _allowedQueryParameters; - private readonly string _redactedPlaceholder; - private readonly HashSet _allowedHeaders; - - [ThreadStatic] - private static StringBuilder? s_cachedStringBuilder; - private const int MaxCachedStringBuilderCapacity = 1024; - - internal static HttpMessageSanitizer Default = new HttpMessageSanitizer(Array.Empty(), Array.Empty()); - - public HttpMessageSanitizer(string[] allowedQueryParameters, string[] allowedHeaders, string redactedPlaceholder = "REDACTED") - { - _logAllHeaders = allowedHeaders.Contains(LogAllValue); - _logFullQueries = allowedQueryParameters.Contains(LogAllValue); - - _allowedQueryParameters = allowedQueryParameters; - _redactedPlaceholder = redactedPlaceholder; - _allowedHeaders = new HashSet(allowedHeaders, StringComparer.InvariantCultureIgnoreCase); - } - - public string SanitizeHeader(string name, string value) - { - if (_logAllHeaders || _allowedHeaders.Contains(name)) - { - return value; - } - - return _redactedPlaceholder; - } - - public string SanitizeUrl(string url) - { - if (_logFullQueries) - { - return url; - } - -#if NET5_0_OR_GREATER - int indexOfQuerySeparator = url.IndexOf('?', StringComparison.Ordinal); -#else - int indexOfQuerySeparator = url.IndexOf('?'); -#endif - - if (indexOfQuerySeparator == -1) - { - return url; - } - - // PERF: Avoid allocations in this heavily-used method: - // 1. Use ReadOnlySpan to avoid creating substrings. - // 2. Defer creating a StringBuilder until absolutely necessary. - // 3. Use a rented StringBuilder to avoid allocating a new one - // each time. - - // Create the StringBuilder only when necessary (when we encounter - // a query parameter that needs to be redacted) - StringBuilder? stringBuilder = null; - - // Keeps track of the number of characters we've processed so far - // so that, if we need to create a StringBuilder, we know how many - // characters to copy over from the original URL. - int lengthSoFar = indexOfQuerySeparator + 1; - - ReadOnlySpan query = url.AsSpan(indexOfQuerySeparator + 1); // +1 to skip the '?' - - while (query.Length > 0) - { - int endOfParameterValue = query.IndexOf('&'); - int endOfParameterName = query.IndexOf('='); - bool noValue = false; - - // Check if we have parameter without value - if ((endOfParameterValue == -1 && endOfParameterName == -1) || - (endOfParameterValue != -1 && (endOfParameterName == -1 || endOfParameterName > endOfParameterValue))) - { - endOfParameterName = endOfParameterValue; - noValue = true; - } - - if (endOfParameterName == -1) - { - endOfParameterName = query.Length; - } - - if (endOfParameterValue == -1) - { - endOfParameterValue = query.Length; - } - else - { - // include the separator - endOfParameterValue++; - } - - ReadOnlySpan parameterName = query.Slice(0, endOfParameterName); - - bool isAllowed = false; - foreach (string name in _allowedQueryParameters) - { - if (parameterName.Equals(name.AsSpan(), StringComparison.OrdinalIgnoreCase)) - { - isAllowed = true; - break; - } - } - - int valueLength = endOfParameterValue; - int nameLength = endOfParameterName; - - if (isAllowed || noValue) - { - if (stringBuilder is null) - { - lengthSoFar += valueLength; - } - else - { - AppendReadOnlySpan(stringBuilder, query.Slice(0, valueLength)); - } - } - else - { - // Encountered a query value that needs to be redacted. - // Create the StringBuilder if we haven't already. - stringBuilder ??= RentStringBuilder(url.Length).Append(url, 0, lengthSoFar); - - AppendReadOnlySpan(stringBuilder, query.Slice(0, nameLength)) - .Append('=') - .Append(_redactedPlaceholder); - - if (query[endOfParameterValue - 1] == '&') - { - stringBuilder.Append('&'); - } - } - - query = query.Slice(valueLength); - } - - return stringBuilder is null ? url : ToStringAndReturnStringBuilder(stringBuilder); - - static StringBuilder AppendReadOnlySpan(StringBuilder builder, ReadOnlySpan span) - { -#if NET6_0_OR_GREATER - return builder.Append(span); -#else - foreach (char c in span) - { - builder.Append(c); - } - - return builder; -#endif - } - } - - private static StringBuilder RentStringBuilder(int capacity) - { - if (capacity <= MaxCachedStringBuilderCapacity) - { - StringBuilder? builder = s_cachedStringBuilder; - if (builder is not null && builder.Capacity >= capacity) - { - s_cachedStringBuilder = null; - return builder; - } - } - - return new StringBuilder(capacity); - } - - private static string ToStringAndReturnStringBuilder(StringBuilder builder) - { - string result = builder.ToString(); - if (builder.Capacity <= MaxCachedStringBuilderCapacity) - { - s_cachedStringBuilder = builder.Clear(); - } - - return result; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/HttpPipelineExtensions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/HttpPipelineExtensions.cs deleted file mode 100644 index 231f13cf53..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/HttpPipelineExtensions.cs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; - -namespace Azure.Core -{ - internal static class HttpPipelineExtensions - { - public static async ValueTask ProcessMessageAsync(this HttpPipeline pipeline, HttpMessage message, RequestContext? requestContext, CancellationToken cancellationToken = default) - { - var (userCt, statusOption) = ApplyRequestContext(requestContext); - if (!userCt.CanBeCanceled || !cancellationToken.CanBeCanceled) - { - await pipeline.SendAsync(message, cancellationToken.CanBeCanceled ? cancellationToken : userCt).ConfigureAwait(false); - } - else - { - using var cts = CancellationTokenSource.CreateLinkedTokenSource(userCt, cancellationToken); - await pipeline.SendAsync(message, cts.Token).ConfigureAwait(false); - } - - if (!message.Response.IsError || statusOption == ErrorOptions.NoThrow) - { - return message.Response; - } - - throw new RequestFailedException(message.Response); - } - - public static Response ProcessMessage(this HttpPipeline pipeline, HttpMessage message, RequestContext? requestContext, CancellationToken cancellationToken = default) - { - var (userCt, statusOption) = ApplyRequestContext(requestContext); - if (!userCt.CanBeCanceled || !cancellationToken.CanBeCanceled) - { - pipeline.Send(message, cancellationToken.CanBeCanceled ? cancellationToken : userCt); - } - else - { - using var cts = CancellationTokenSource.CreateLinkedTokenSource(userCt, cancellationToken); - pipeline.Send(message, cts.Token); - } - - if (!message.Response.IsError || statusOption == ErrorOptions.NoThrow) - { - return message.Response; - } - - throw new RequestFailedException(message.Response); - } - - public static async ValueTask> ProcessHeadAsBoolMessageAsync(this HttpPipeline pipeline, HttpMessage message, ClientDiagnostics clientDiagnostics, RequestContext? requestContext) - { - var response = await pipeline.ProcessMessageAsync(message, requestContext).ConfigureAwait(false); - switch (response.Status) - { - case >= 200 and < 300: - return Response.FromValue(true, response); - case >= 400 and < 500: - return Response.FromValue(false, response); - default: - return new ErrorResponse(response, new RequestFailedException(response)); - } - } - - public static Response ProcessHeadAsBoolMessage(this HttpPipeline pipeline, HttpMessage message, ClientDiagnostics clientDiagnostics, RequestContext? requestContext) - { - var response = pipeline.ProcessMessage(message, requestContext); - switch (response.Status) - { - case >= 200 and < 300: - return Response.FromValue(true, response); - case >= 400 and < 500: - return Response.FromValue(false, response); - default: - return new ErrorResponse(response, new RequestFailedException(response)); - } - } - - private static (CancellationToken CancellationToken, ErrorOptions ErrorOptions) ApplyRequestContext(RequestContext? requestContext) - { - if (requestContext == null) - { - return (CancellationToken.None, ErrorOptions.Default); - } - - return (requestContext.CancellationToken, requestContext.ErrorOptions); - } - - internal class ErrorResponse : Response - { - private readonly Response _response; - private readonly RequestFailedException _exception; - - public ErrorResponse(Response response, RequestFailedException exception) - { - _response = response; - _exception = exception; - } - - public override T Value { get => throw _exception; } - - public override Response GetRawResponse() => _response; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/IOperationSource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/IOperationSource.cs deleted file mode 100644 index 1be2f9b733..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/IOperationSource.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.Threading; -using System.Threading.Tasks; - -namespace Azure.Core -{ - internal interface IOperationSource - { - T CreateResult(Response response, CancellationToken cancellationToken); - ValueTask CreateResultAsync(Response response, CancellationToken cancellationToken); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/IUtf8JsonSerializable.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/IUtf8JsonSerializable.cs deleted file mode 100644 index 5653e46093..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/IUtf8JsonSerializable.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System.Text.Json; - -namespace Azure.Core -{ - internal interface IUtf8JsonSerializable - { - void Write(Utf8JsonWriter writer); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/InitializationConstructorAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/InitializationConstructorAttribute.cs deleted file mode 100644 index d087b58c2a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/InitializationConstructorAttribute.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -namespace Azure.Core -{ - /// - /// An attribute class indicating to AutoRest which constructor to use for initialization. - /// - [AttributeUsage(AttributeTargets.Constructor)] - internal class InitializationConstructorAttribute : Attribute - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ManagedServiceIdentityTypeV3Converter.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ManagedServiceIdentityTypeV3Converter.cs deleted file mode 100644 index b33c186e19..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ManagedServiceIdentityTypeV3Converter.cs +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace Azure.ResourceManager.Models -{ - /// JsonConverter for managed service identity type v3. - internal class ManagedServiceIdentityTypeV3Converter : JsonConverter - { - internal const string SystemAssignedUserAssignedV3Value = "SystemAssigned,UserAssigned"; - - /// Serialize managed service identity type to v3 format. - /// The writer. - /// The ManagedServiceIdentityType model which is v4. - /// The options for JsonSerializer. - public override void Write(Utf8JsonWriter writer, ManagedServiceIdentityType model, JsonSerializerOptions options) - { - writer.WritePropertyName("type"); - if (model == ManagedServiceIdentityType.SystemAssignedUserAssigned) - { - writer.WriteStringValue(SystemAssignedUserAssignedV3Value); - } - else - { - writer.WriteStringValue(model.ToString()); - } - } - - /// Deserialize managed service identity type from v3 format. - /// The reader. - /// The type to convert - /// The options for JsonSerializer. - public override ManagedServiceIdentityType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - foreach (var property in document.RootElement.EnumerateObject()) - { - var typeValue = property.Value.GetString(); - if (typeValue.Equals(SystemAssignedUserAssignedV3Value, StringComparison.OrdinalIgnoreCase)) - { - return ManagedServiceIdentityType.SystemAssignedUserAssigned; - } - return new ManagedServiceIdentityType(typeValue); - } - return null; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/NextLinkOperationImplementation.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/NextLinkOperationImplementation.cs deleted file mode 100644 index d4dc0403e2..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/NextLinkOperationImplementation.cs +++ /dev/null @@ -1,701 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; - -namespace Azure.Core -{ - internal class NextLinkOperationImplementation : IOperation - { - internal const string NotSet = "NOT_SET"; - internal const string RehydrationTokenVersion = "1.0.0"; - private const string ApiVersionParam = "api-version"; - private static readonly string[] FailureStates = { "failed", "canceled" }; - private static readonly string[] SuccessStates = { "succeeded" }; - - private readonly HeaderSource _headerSource; - private readonly Uri _startRequestUri; - private readonly OperationFinalStateVia _finalStateVia; - private readonly HttpPipeline _pipeline; - private readonly string? _apiVersion; - - private string? _lastKnownLocation; - private string _nextRequestUri; - - // We can only get OperationId when - // - The operation is still in progress and nextRequestUri contains it - // - During rehydration, rehydrationToken.Id is the operation id - public string OperationId { get; private set; } = NotSet; - public RequestMethod RequestMethod { get; } - - public static IOperation Create( - HttpPipeline pipeline, - RequestMethod requestMethod, - Uri startRequestUri, - Response response, - OperationFinalStateVia finalStateVia, - bool skipApiVersionOverride = false, - string? apiVersionOverrideValue = null) - { - string? apiVersionStr = null; - if (apiVersionOverrideValue is not null) - { - apiVersionStr = apiVersionOverrideValue; - } - else - { - apiVersionStr = !skipApiVersionOverride && TryGetApiVersion(startRequestUri, out ReadOnlySpan apiVersion) ? apiVersion.ToString() : null; - } - var headerSource = GetHeaderSource(requestMethod, startRequestUri, response, apiVersionStr, out string nextRequestUri, out bool isNextRequestPolling); - - string? lastKnownLocation; - if (!response.Headers.TryGetValue("Location", out lastKnownLocation)) - { - lastKnownLocation = null; - } - - NextLinkOperationImplementation operation = new(pipeline, requestMethod, startRequestUri, nextRequestUri, headerSource, lastKnownLocation, finalStateVia, apiVersionStr, isNextRequestPolling: isNextRequestPolling); - - if (headerSource == HeaderSource.None && IsFinalState(response, headerSource, out var failureState, out _)) - { - return new CompletedOperation(failureState ?? GetOperationStateFromFinalResponse(requestMethod, response), operation); - } - - return operation; - } - - public static IOperation Create( - IOperationSource operationSource, - HttpPipeline pipeline, - RequestMethod requestMethod, - Uri startRequestUri, - Response response, - OperationFinalStateVia finalStateVia, - bool skipApiVersionOverride = false, - string? apiVersionOverrideValue = null) - { - var operation = Create(pipeline, requestMethod, startRequestUri, response, finalStateVia, skipApiVersionOverride, apiVersionOverrideValue); - return new OperationToOperationOfT(operationSource, operation); - } - - public static IOperation Create( - IOperationSource operationSource, - IOperation operation) - => new OperationToOperationOfT(operationSource, operation); - - public static IOperation Create( - HttpPipeline pipeline, - RehydrationToken rehydrationToken) - { - AssertNotNull(rehydrationToken, nameof(rehydrationToken)); - AssertNotNull(pipeline, nameof(pipeline)); - - // TODO: Once we remove NextLinkOperationImplementation from internal shared and make it internal to Azure.Core only in https://github.com/Azure/azure-sdk-for-net/issues/43260 - // We can access the internal members from RehydrationToken directly - var data = ModelReaderWriter.Write(rehydrationToken!, ModelReaderWriterOptions.Json, AzureCoreContext.Default); - using var document = JsonDocument.Parse(data); - var lroDetails = document.RootElement; - - // We are sure that the following properties exists in the serialized rehydrationToken - var initialUri = lroDetails.GetProperty("initialUri").GetString(); - if (!Uri.TryCreate(initialUri, UriKind.Absolute, out var startRequestUri)) - { - throw new ArgumentException($"\"initialUri\" property on \"rehydrationToken\" is an invalid Uri", nameof(rehydrationToken)); - } - - // We are sure that the following properties(apart from nullable lastKnownLocation) are not null as they are required in the rehydrationToken - string nextRequestUri = lroDetails.GetProperty("nextRequestUri").GetString()!; - string requestMethodStr = lroDetails.GetProperty("requestMethod").GetString()!; - RequestMethod requestMethod = new RequestMethod(requestMethodStr)!; - string? lastKnownLocation = lroDetails.GetProperty("lastKnownLocation").GetString(); - - string finalStateViaStr = lroDetails.GetProperty("finalStateVia").GetString()!; - OperationFinalStateVia finalStateVia; - if (Enum.IsDefined(typeof(OperationFinalStateVia), finalStateViaStr)) - { - finalStateVia = (OperationFinalStateVia)Enum.Parse(typeof(OperationFinalStateVia), finalStateViaStr); - } - else - { - finalStateVia = OperationFinalStateVia.Location; - } - - string headerSourceStr = lroDetails.GetProperty("headerSource").GetString()!; - HeaderSource headerSource; - if (Enum.IsDefined(typeof(HeaderSource), headerSourceStr)) - { - headerSource = (HeaderSource)Enum.Parse(typeof(HeaderSource), headerSourceStr); - } - else - { - headerSource = HeaderSource.None; - } - - return new NextLinkOperationImplementation(pipeline, requestMethod, startRequestUri, nextRequestUri, headerSource, lastKnownLocation, finalStateVia, null, rehydrationToken.Id); - } - - private NextLinkOperationImplementation( - HttpPipeline pipeline, - RequestMethod requestMethod, - Uri startRequestUri, - string nextRequestUri, - HeaderSource headerSource, - string? lastKnownLocation, - OperationFinalStateVia finalStateVia, - string? apiVersion, - string? operationId = null, - bool isNextRequestPolling = false) - { - AssertNotNull(pipeline, nameof(pipeline)); - AssertNotNull(requestMethod, nameof(requestMethod)); - AssertNotNull(startRequestUri, nameof(startRequestUri)); - AssertNotNull(nextRequestUri, nameof(nextRequestUri)); - AssertNotNull(headerSource, nameof(headerSource)); - AssertNotNull(finalStateVia, nameof(finalStateVia)); - - RequestMethod = requestMethod; - _headerSource = headerSource; - _startRequestUri = startRequestUri; - _nextRequestUri = nextRequestUri; - _lastKnownLocation = lastKnownLocation; - _finalStateVia = finalStateVia; - _pipeline = pipeline; - _apiVersion = apiVersion; - if (operationId is not null) - { - OperationId = operationId; - } - else if (isNextRequestPolling) - { - OperationId = ParseOperationId(startRequestUri, nextRequestUri); - } - } - - private static string ParseOperationId(Uri startRequestUri, string nextRequestUri) - { - if (Uri.TryCreate(nextRequestUri, UriKind.Absolute, out var nextLink) && nextLink.Scheme != "file") - { - return nextLink.Segments.Last(); - } - else - { - return new Uri(startRequestUri, nextRequestUri).Segments.Last(); - } - } - - public RehydrationToken GetRehydrationToken() - => GetRehydrationToken(RequestMethod, _startRequestUri, _nextRequestUri, _headerSource.ToString(), _lastKnownLocation, _finalStateVia.ToString(), OperationId); - - public static RehydrationToken GetRehydrationToken( - RequestMethod requestMethod, - Uri startRequestUri, - Response response, - OperationFinalStateVia finalStateVia) - { - AssertNotNull(requestMethod, nameof(requestMethod)); - AssertNotNull(startRequestUri, nameof(startRequestUri)); - AssertNotNull(response, nameof(response)); - AssertNotNull(finalStateVia, nameof(finalStateVia)); - - var headerSource = GetHeaderSource(requestMethod, startRequestUri, response, null, out string nextRequestUri, out bool isNextRequestPolling); - string? lastKnownLocation; - if (!response.Headers.TryGetValue("Location", out lastKnownLocation)) - { - lastKnownLocation = null; - } - return GetRehydrationToken(requestMethod, startRequestUri, nextRequestUri, headerSource.ToString(), lastKnownLocation, finalStateVia.ToString(), isNextRequestPolling ? ParseOperationId(startRequestUri, nextRequestUri) : null); - } - - public static RehydrationToken GetRehydrationToken( - RequestMethod requestMethod, - Uri startRequestUri, - string nextRequestUri, - string headerSource, - string? lastKnownLocation, - string finalStateVia, - string? operationId = null) - { - // TODO: Once we remove NextLinkOperationImplementation from internal shared and make it internal to Azure.Core only in https://github.com/Azure/azure-sdk-for-net/issues/43260 - // We can access the internal members from RehydrationToken directly - var json = $$""" - {"version":"{{RehydrationTokenVersion}}","id":{{ConstructStringValue(operationId)}},"requestMethod":"{{requestMethod}}","initialUri":"{{startRequestUri.AbsoluteUri}}","nextRequestUri":"{{nextRequestUri}}","headerSource":"{{headerSource}}","finalStateVia":"{{finalStateVia}}","lastKnownLocation":{{ConstructStringValue(lastKnownLocation)}}} - """; - var data = new BinaryData(json); - return ModelReaderWriter.Read(data, ModelReaderWriterOptions.Json, AzureCoreContext.Default); - } - - private static string? ConstructStringValue(string? value) => value is null ? "null" : $"\"{value}\""; - - public async ValueTask UpdateStateAsync(bool async, CancellationToken cancellationToken) - { - Response response = async - ? await GetResponseAsync(_nextRequestUri, cancellationToken).ConfigureAwait(false) - : GetResponse(_nextRequestUri, cancellationToken); - - var hasCompleted = IsFinalState(response, _headerSource, out var failureState, out var resourceLocation); - if (failureState != null) - { - return failureState.Value; - } - - if (hasCompleted) - { - string? finalUri = GetFinalUri(resourceLocation); - Response finalResponse; - if (finalUri != null) - { - finalResponse = async - ? await GetResponseAsync(finalUri, cancellationToken).ConfigureAwait(false) - : GetResponse(finalUri, cancellationToken); - } - else - { - finalResponse = response; - } - return GetOperationStateFromFinalResponse(RequestMethod, finalResponse); - } - - UpdateNextRequestUri(response.Headers); - return OperationState.Pending(response); - } - - private static OperationState GetOperationStateFromFinalResponse(RequestMethod requestMethod, Response response) - { - switch (response.Status) - { - case 200: - case 201 when requestMethod == RequestMethod.Put: - case 204 when requestMethod != RequestMethod.Put && requestMethod != RequestMethod.Patch: - return OperationState.Success(response); - default: - return OperationState.Failure(response); - } - } - - private void UpdateNextRequestUri(ResponseHeaders headers) - { - var hasLocation = headers.TryGetValue("Location", out string? location); - if (hasLocation) - { - _lastKnownLocation = location; - } - - switch (_headerSource) - { - case HeaderSource.OperationLocation when headers.TryGetValue("Operation-Location", out string? operationLocation): - _nextRequestUri = AppendOrReplaceApiVersion(operationLocation, _apiVersion); - OperationId = ParseOperationId(_startRequestUri, _nextRequestUri); - return; - case HeaderSource.AzureAsyncOperation when headers.TryGetValue("Azure-AsyncOperation", out string? azureAsyncOperation): - _nextRequestUri = AppendOrReplaceApiVersion(azureAsyncOperation, _apiVersion); - OperationId = ParseOperationId(_startRequestUri, _nextRequestUri); - return; - case HeaderSource.Location when hasLocation: - _nextRequestUri = AppendOrReplaceApiVersion(location!, _apiVersion); - OperationId = ParseOperationId(_startRequestUri, _nextRequestUri); - return; - } - } - - internal static string AppendOrReplaceApiVersion(string uri, string? apiVersion) - { - if (!string.IsNullOrEmpty(apiVersion)) - { - var uriSpan = uri.AsSpan(); - var apiVersionParamSpan = ApiVersionParam.AsSpan(); - var apiVersionIndex = uriSpan.IndexOf(apiVersionParamSpan); - if (apiVersionIndex == -1) - { - var concatSymbol = uriSpan.IndexOf('?') > -1 ? "&" : "?"; - return $"{uri}{concatSymbol}api-version={apiVersion}"; - } - else - { - var lengthToEndOfApiVersionParam = apiVersionIndex + ApiVersionParam.Length; - ReadOnlySpan remaining = uriSpan.Slice(lengthToEndOfApiVersionParam); - bool apiVersionHasEqualSign = false; - if (remaining.IndexOf('=') == 0) - { - remaining = remaining.Slice(1); - lengthToEndOfApiVersionParam += 1; - apiVersionHasEqualSign = true; - } - var indexOfFirstSignAfterApiVersion = remaining.IndexOf('&'); - ReadOnlySpan uriBeforeApiVersion = uriSpan.Slice(0, lengthToEndOfApiVersionParam); - if (indexOfFirstSignAfterApiVersion == -1) - { - return string.Concat(uriBeforeApiVersion.ToString(), apiVersionHasEqualSign ? string.Empty : "=", apiVersion); - } - else - { - ReadOnlySpan uriAfterApiVersion = uriSpan.Slice(indexOfFirstSignAfterApiVersion + lengthToEndOfApiVersionParam); - return string.Concat(uriBeforeApiVersion.ToString(), apiVersionHasEqualSign ? string.Empty : "=", apiVersion, uriAfterApiVersion.ToString()); - } - } - } - return uri; - } - - internal static bool TryGetApiVersion(Uri startRequestUri, out ReadOnlySpan apiVersion) - { - apiVersion = default; - ReadOnlySpan uriSpan = startRequestUri.Query.AsSpan(); - int startIndex = uriSpan.IndexOf(ApiVersionParam.AsSpan()); - if (startIndex == -1) - { - return false; - } - startIndex += ApiVersionParam.Length; - ReadOnlySpan remaining = uriSpan.Slice(startIndex); - if (remaining.IndexOf('=') == 0) - { - remaining = remaining.Slice(1); - startIndex += 1; - } - else - { - return false; - } - int endIndex = remaining.IndexOf('&'); - int length = endIndex == -1 ? uriSpan.Length - startIndex : endIndex; - apiVersion = uriSpan.Slice(startIndex, length); - return true; - } - - /// - /// This function is used to get the final request uri after the lro has completed. - /// - private string? GetFinalUri(string? resourceLocation) - { - // Set final uri as null if the response for initial request doesn't contain header "Operation-Location" or "Azure-AsyncOperation". - if (_headerSource is not (HeaderSource.OperationLocation or HeaderSource.AzureAsyncOperation)) - { - return null; - } - - // Set final uri as null if initial request is a delete method. - if (RequestMethod == RequestMethod.Delete) - { - return null; - } - - // Handle final-state-via options: https://github.com/Azure/autorest/blob/main/docs/extensions/readme.md#x-ms-long-running-operation-options - switch (_finalStateVia) - { - case OperationFinalStateVia.LocationOverride when !string.IsNullOrEmpty(_lastKnownLocation): - return _lastKnownLocation; - case OperationFinalStateVia.OperationLocation or OperationFinalStateVia.AzureAsyncOperation when RequestMethod == RequestMethod.Post: - return null; - case OperationFinalStateVia.OriginalUri: - return _startRequestUri.AbsoluteUri; - } - - // If response body contains resourceLocation, use it: https://github.com/microsoft/api-guidelines/blob/vNext/Guidelines.md#target-resource-location - if (resourceLocation != null) - { - return resourceLocation; - } - - // If initial request is PUT or PATCH, return initial request Uri - if (RequestMethod == RequestMethod.Put || RequestMethod == RequestMethod.Patch) - { - return _startRequestUri.AbsoluteUri; - } - - // If response for initial request contains header "Location", return last known location - if (!string.IsNullOrEmpty(_lastKnownLocation)) - { - return _lastKnownLocation; - } - - return null; - } - - private Response GetResponse(string uri, CancellationToken cancellationToken) - { - using HttpMessage message = CreateRequest(uri); - _pipeline.Send(message, cancellationToken); - - // If we are doing final get for a delete LRO with 404, just return empty response with 204 - if (message.Response.Status == 404 && RequestMethod == RequestMethod.Delete) - { - return new EmptyResponse(HttpStatusCode.NoContent, message.Response.ClientRequestId); - } - return message.Response; - } - - private async ValueTask GetResponseAsync(string uri, CancellationToken cancellationToken) - { - using HttpMessage message = CreateRequest(uri); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - - // If we are doing final get for a delete LRO with 404, just return empty response with 204 - if (message.Response.Status == 404 && RequestMethod == RequestMethod.Delete) - { - return new EmptyResponse(HttpStatusCode.NoContent, message.Response.ClientRequestId); - } - return message.Response; - } - - /// - /// This is only used for final get of the delete LRO, we just want to return an empty response with 204 to the user for this case. - /// - private sealed class EmptyResponse : Response - { - public EmptyResponse(HttpStatusCode status, string clientRequestId) - { - Status = (int)status; - ReasonPhrase = status.ToString(); - ClientRequestId = clientRequestId; - } - - public override int Status { get; } - - public override string ReasonPhrase { get; } - - public override Stream? ContentStream { get => null; set => throw new InvalidOperationException("Should not set ContentStream for an empty response."); } - public override string ClientRequestId { get; set; } - - public override void Dispose() - { - } - - /// -#if HAS_INTERNALS_VISIBLE_CORE - internal -#endif - protected override bool ContainsHeader(string name) => false; - - /// -#if HAS_INTERNALS_VISIBLE_CORE - internal -#endif - protected override IEnumerable EnumerateHeaders() => Array.Empty(); - - /// -#if HAS_INTERNALS_VISIBLE_CORE - internal -#endif - protected override bool TryGetHeader(string name, out string value) - { - value = string.Empty; - return false; - } - - /// -#if HAS_INTERNALS_VISIBLE_CORE - internal -#endif - protected override bool TryGetHeaderValues(string name, out IEnumerable values) - { - values = Array.Empty(); - return false; - } - } - - private HttpMessage CreateRequest(string uri) - { - HttpMessage message = _pipeline.CreateMessage(); - Request request = message.Request; - request.Method = RequestMethod.Get; - - if (Uri.TryCreate(uri, UriKind.Absolute, out var nextLink) && nextLink.Scheme != "file") - { - request.Uri.Reset(nextLink); - } - else - { - request.Uri.Reset(new Uri(_startRequestUri, uri)); - } - - return message; - } - - private static bool IsFinalState(Response response, HeaderSource headerSource, out OperationState? failureState, out string? resourceLocation) - { - failureState = null; - resourceLocation = null; - - if (headerSource == HeaderSource.Location) - { - return response.Status != 202; - } - - if (response.Status is >= 200 and <= 204) - { - if (response.ContentStream is { Length: > 0 }) - { - try - { - using JsonDocument document = JsonDocument.Parse(response.ContentStream); - var root = document.RootElement; - switch (headerSource) - { - case HeaderSource.None when root.TryGetProperty("properties", out var properties) && properties.TryGetProperty("provisioningState", out JsonElement property): - case HeaderSource.OperationLocation when root.TryGetProperty("status", out property): - case HeaderSource.AzureAsyncOperation when root.TryGetProperty("status", out property): - var state = GetRequiredString(property).ToLowerInvariant(); - if (FailureStates.Contains(state)) - { - failureState = OperationState.Failure(response); - return true; - } - else if (!SuccessStates.Contains(state)) - { - return false; - } - else - { - if (headerSource is HeaderSource.OperationLocation or HeaderSource.AzureAsyncOperation && root.TryGetProperty("resourceLocation", out var resourceLocationProperty)) - { - resourceLocation = resourceLocationProperty.GetString(); - } - return true; - } - } - } - finally - { - // It is required to reset the position of the content after reading as this response may be used for deserialization. - response.ContentStream.Position = 0; - } - } - - // If headerSource is None and provisioningState was not found, it defaults to Succeeded. - if (headerSource == HeaderSource.None) - { - return true; - } - } - - failureState = OperationState.Failure(response); - return true; - } - - private static string GetRequiredString(in JsonElement element) - { - var value = element.GetString(); - if (value == null) - throw new InvalidOperationException($"The requested operation requires an element of type 'String', but the target element has type '{element.ValueKind}'."); - - return value; - } - - private static bool ShouldIgnoreHeader(RequestMethod method, Response response) - => method.Method == RequestMethod.Patch.Method && response.Status == 200; - - // Since this method is static, we can't manipulate the instance property OperationId of the class. We need to return isRequestPolling to update the OperationId after creaing the instance. - private static HeaderSource GetHeaderSource(RequestMethod requestMethod, Uri requestUri, Response response, string? apiVersion, out string nextRequestUri, out bool isNextRequestPolling) - { - isNextRequestPolling = false; - if (ShouldIgnoreHeader(requestMethod, response)) - { - nextRequestUri = requestUri.AbsoluteUri; - return HeaderSource.None; - } - - var headers = response.Headers; - if (headers.TryGetValue("Operation-Location", out var operationLocationUri)) - { - nextRequestUri = AppendOrReplaceApiVersion(operationLocationUri, apiVersion); - isNextRequestPolling = true; - return HeaderSource.OperationLocation; - } - - if (headers.TryGetValue("Azure-AsyncOperation", out var azureAsyncOperationUri)) - { - nextRequestUri = AppendOrReplaceApiVersion(azureAsyncOperationUri, apiVersion); - isNextRequestPolling = true; - return HeaderSource.AzureAsyncOperation; - } - - if (headers.TryGetValue("Location", out var locationUri)) - { - nextRequestUri = AppendOrReplaceApiVersion(locationUri, apiVersion); - isNextRequestPolling = true; - return HeaderSource.Location; - } - - nextRequestUri = requestUri.AbsoluteUri; - return HeaderSource.None; - } - - private static void AssertNotNull(T value, string name) - { - if (value is null) - { - throw new ArgumentNullException(name); - } - } - - private enum HeaderSource - { - None, - OperationLocation, - AzureAsyncOperation, - Location - } - - private class CompletedOperation : IOperation - { - private readonly OperationState _operationState; - - private readonly NextLinkOperationImplementation _operation; - - public CompletedOperation(OperationState operationState, NextLinkOperationImplementation operation) - { - _operationState = operationState; - _operation = operation; - } - - public ValueTask UpdateStateAsync(bool async, CancellationToken cancellationToken) => new(_operationState); - - public RehydrationToken GetRehydrationToken() => _operation.GetRehydrationToken(); - } - - private sealed class OperationToOperationOfT : IOperation - { - private readonly IOperationSource _operationSource; - private readonly IOperation _operation; - - public OperationToOperationOfT(IOperationSource operationSource, IOperation operation) - { - _operationSource = operationSource; - _operation = operation; - } - - public async ValueTask> UpdateStateAsync(bool async, CancellationToken cancellationToken) - { - var state = await _operation.UpdateStateAsync(async, cancellationToken).ConfigureAwait(false); - if (state.HasSucceeded) - { - var result = async - ? await _operationSource.CreateResultAsync(state.RawResponse, cancellationToken).ConfigureAwait(false) - : _operationSource.CreateResult(state.RawResponse, cancellationToken); - - return OperationState.Success(state.RawResponse, result); - } - - if (state.HasCompleted) - { - return OperationState.Failure(state.RawResponse, state.OperationFailedException); - } - - return OperationState.Pending(state.RawResponse); - } - - public RehydrationToken GetRehydrationToken() => _operation.GetRehydrationToken(); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/NoValueResponseOfT.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/NoValueResponseOfT.cs deleted file mode 100644 index 95fa1e2573..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/NoValueResponseOfT.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -namespace Azure -{ -#pragma warning disable SA1649 // File name should match first type name - internal sealed class NoValueResponse : NullableResponse -#pragma warning restore SA1649 // File name should match first type name - { - private readonly Response _response; - - public NoValueResponse(Response response) - { - _response = response ?? throw new ArgumentNullException(nameof(response)); - } - - /// - public override bool HasValue => false; - - public override T Value - { - get - { - throw new InvalidOperationException(GetStatusMessage()); - } - } - - public override Response GetRawResponse() => _response; - - public override string ToString() - { - return GetStatusMessage(); - } - - internal string GetStatusMessage() => $"Status: {GetRawResponse().Status}, Service returned no content"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationFinalStateVia.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationFinalStateVia.cs deleted file mode 100644 index 8ad2396db9..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationFinalStateVia.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -namespace Azure.Core -{ - internal enum OperationFinalStateVia - { - AzureAsyncOperation, - Location, - OriginalUri, - OperationLocation, - LocationOverride, - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationInternal.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationInternal.cs deleted file mode 100644 index 2435465459..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationInternal.cs +++ /dev/null @@ -1,263 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; - -#nullable enable - -namespace Azure.Core -{ - /// - /// A helper class used to build long-running operation instances. In order to use this helper: - /// - /// Make sure your LRO implements the interface. - /// Add a private field to your LRO, and instantiate it during construction. - /// Delegate method calls to the implementations. - /// - /// Supported members: - /// - /// - /// - /// - /// - /// , used for - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - internal class OperationInternal : OperationInternalBase - { - // To minimize code duplication and avoid introduction of another type, - // OperationInternal delegates implementation to the OperationInternal. - // VoidValue is a private empty struct which only purpose is to be used as generic parameter. - private readonly OperationInternal _internalOperation; - - /// - /// Initializes a new instance of the class in a final successful state. - /// - /// The final value of . - public static OperationInternal Succeeded(Response rawResponse) => new(OperationState.Success(rawResponse)); - - /// - /// Initializes a new instance of the class in a final failed state. - /// - /// The final value of . - /// The exception that will be thrown by UpdateStatusAsync. - public static OperationInternal Failed(Response rawResponse, RequestFailedException operationFailedException) => new(OperationState.Failure(rawResponse, operationFailedException)); - - /// - /// Initializes a new instance of the class. - /// - /// The long-running operation making use of this class. Passing "this" is expected. - /// Used for diagnostic scope and exception creation. This is expected to be the instance created during the construction of your main client. - /// - /// The initial value of . Usually, long-running operation objects can be instantiated in two ways: - /// - /// - /// When calling a client's "Start<OperationName>" method, a service call is made to start the operation, and an instance is returned. - /// In this case, the response received from this service call can be passed here. - /// - /// - /// When a user instantiates an directly using a public constructor, there's no previous service call. In this case, passing null is expected. - /// - /// - /// - /// - /// The type name of the long-running operation making use of this class. Used when creating diagnostic scopes. If left null, the type name will be inferred based on the - /// parameter . - /// - /// The attributes to use during diagnostic scope creation. - /// The delay strategy to use. Default is . - public OperationInternal(IOperation operation, - ClientDiagnostics clientDiagnostics, - Response rawResponse, - string? operationTypeName = null, - IEnumerable>? scopeAttributes = null, - DelayStrategy? fallbackStrategy = null) - : base(clientDiagnostics, operationTypeName ?? operation.GetType().Name, scopeAttributes, fallbackStrategy) - { - _internalOperation = new OperationInternal(new OperationToOperationOfTProxy(operation), clientDiagnostics, rawResponse, operationTypeName ?? operation.GetType().Name, scopeAttributes, fallbackStrategy); - } - - internal OperationInternal(OperationState finalState) - : base(finalState.RawResponse) - { - _internalOperation = finalState.HasSucceeded - ? OperationInternal.Succeeded(finalState.RawResponse, default) - : OperationInternal.Failed(finalState.RawResponse, finalState.OperationFailedException!); - } - - public override Response RawResponse => _internalOperation.RawResponse; - - public override bool HasCompleted => _internalOperation.HasCompleted; - - protected override async ValueTask UpdateStatusAsync(bool async, CancellationToken cancellationToken) => - async ? await _internalOperation.UpdateStatusAsync(cancellationToken).ConfigureAwait(false) : _internalOperation.UpdateStatus(cancellationToken); - - // Wrapper type that converts OperationState to OperationState and can be passed to `OperationInternal` constructor. - private class OperationToOperationOfTProxy : IOperation - { - private readonly IOperation _operation; - - public OperationToOperationOfTProxy(IOperation operation) - { - _operation = operation; - } - - public RehydrationToken GetRehydrationToken() => _operation.GetRehydrationToken(); - - public async ValueTask> UpdateStateAsync(bool async, CancellationToken cancellationToken) - { - var state = await _operation.UpdateStateAsync(async, cancellationToken).ConfigureAwait(false); - if (!state.HasCompleted) - { - return OperationState.Pending(state.RawResponse); - } - - if (state.HasSucceeded) - { - return OperationState.Success(state.RawResponse, new VoidValue()); - } - - return OperationState.Failure(state.RawResponse, state.OperationFailedException); - } - } - } - - /// - /// An interface used by for making service calls and updating state. It's expected that - /// your long-running operation classes implement this interface. - /// - internal interface IOperation - { - /// - /// Calls the service and updates the state of the long-running operation. Properties directly handled by the - /// class, such as - /// don't need to be updated. Operation-specific properties, such as "CreateOn" or "LastModified", - /// must be manually updated by the operation implementing this method. - /// Usage example: - /// - /// async ValueTask<OperationState> IOperation.UpdateStateAsync(bool async, CancellationToken cancellationToken)
- /// {
- /// Response<R> response = async ? <async service call> : <sync service call>;
- /// if (<operation succeeded>) return OperationState.Success(response.GetRawResponse(), <parse response>);
- /// if (<operation failed>) return OperationState.Failure(response.GetRawResponse());
- /// return OperationState.Pending(response.GetRawResponse());
- /// } - ///
- ///
- ///
- /// true if the call should be executed asynchronously. Otherwise, false. - /// A controlling the request lifetime. - /// - /// A structure indicating the current operation state. The structure must be instantiated by one of - /// its static methods: - /// - /// Use when the operation has completed successfully. - /// Use when the operation has completed with failures. - /// Use when the operation has not completed yet. - /// - /// - ValueTask UpdateStateAsync(bool async, CancellationToken cancellationToken); - - /// - /// Get a token that can be used to rehydrate the operation. - /// - RehydrationToken GetRehydrationToken(); - } - - /// - /// A helper structure passed to to indicate the current operation state. This structure must be - /// instantiated by one of its static methods, depending on the operation state: - /// - /// Use when the operation has completed successfully. - /// Use when the operation has completed with failures. - /// Use when the operation has not completed yet. - /// - /// - internal readonly struct OperationState - { - private OperationState(Response rawResponse, bool hasCompleted, bool hasSucceeded, RequestFailedException? operationFailedException) - { - RawResponse = rawResponse; - HasCompleted = hasCompleted; - HasSucceeded = hasSucceeded; - OperationFailedException = operationFailedException; - } - - public Response RawResponse { get; } - - public bool HasCompleted { get; } - - public bool HasSucceeded { get; } - - public RequestFailedException? OperationFailedException { get; } - - /// - /// Instantiates an indicating the operation has completed successfully. - /// - /// The HTTP response obtained during the status update. - /// A new instance. - /// Thrown if is null. - public static OperationState Success(Response rawResponse) - { - if (rawResponse is null) - { - throw new ArgumentNullException(nameof(rawResponse)); - } - - return new OperationState(rawResponse, true, true, default); - } - - /// - /// Instantiates an indicating the operation has completed with failures. - /// - /// The HTTP response obtained during the status update. - /// - /// The exception to throw from UpdateStatus because of the operation failure. If left null, - /// a default exception is created based on the parameter. - /// - /// A new instance. - /// Thrown if is null. - public static OperationState Failure(Response rawResponse, RequestFailedException? operationFailedException = null) - { - if (rawResponse is null) - { - throw new ArgumentNullException(nameof(rawResponse)); - } - - return new OperationState(rawResponse, true, false, operationFailedException); - } - - /// - /// Instantiates an indicating the operation has not completed yet. - /// - /// The HTTP response obtained during the status update. - /// A new instance. - /// Thrown if is null. - public static OperationState Pending(Response rawResponse) - { - if (rawResponse is null) - { - throw new ArgumentNullException(nameof(rawResponse)); - } - - return new OperationState(rawResponse, false, default, default); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationInternalBase.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationInternalBase.cs deleted file mode 100644 index dad6480c22..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationInternalBase.cs +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; - -namespace Azure.Core -{ - internal abstract class OperationInternalBase - { - private readonly ClientDiagnostics _diagnostics; - private readonly IReadOnlyDictionary? _scopeAttributes; - private readonly DelayStrategy? _fallbackStrategy; - private readonly AsyncLockWithValue _responseLock; - - private readonly string _waitForCompletionResponseScopeName; - protected readonly string _updateStatusScopeName; - protected readonly string _waitForCompletionScopeName; - - protected OperationInternalBase(Response rawResponse) - { - _diagnostics = new ClientDiagnostics(ClientOptions.Default); - _updateStatusScopeName = string.Empty; - _waitForCompletionResponseScopeName = string.Empty; - _waitForCompletionScopeName = string.Empty; - _scopeAttributes = default; - _fallbackStrategy = default; - _responseLock = new AsyncLockWithValue(rawResponse); - } - - protected OperationInternalBase(ClientDiagnostics clientDiagnostics, string operationTypeName, IEnumerable>? scopeAttributes = null, DelayStrategy? fallbackStrategy = null) - { - _diagnostics = clientDiagnostics; - _updateStatusScopeName = $"{operationTypeName}.{nameof(UpdateStatus)}"; - _waitForCompletionResponseScopeName = $"{operationTypeName}.{nameof(WaitForCompletionResponse)}"; - _waitForCompletionScopeName = $"{operationTypeName}.WaitForCompletion"; - _scopeAttributes = scopeAttributes?.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); - _fallbackStrategy = fallbackStrategy; - _responseLock = new AsyncLockWithValue(); - } - - /// - /// The last HTTP response received from the server. Its update already handled in calls to "UpdateStatus" and - /// "WaitForCompletionAsync", but custom methods not supported by this class, such as "CancelOperation", - /// must update it as well. - /// Usage example: - /// - /// public Response GetRawResponse() => _operationInternal.RawResponse; - /// - /// - /// - public abstract Response RawResponse { get; } - - /// - /// Returns true if the long-running operation has completed. - /// Usage example: - /// - /// public bool HasCompleted => _operationInternal.HasCompleted; - /// - /// - /// - public abstract bool HasCompleted { get; } - - /// - /// Calls the server to get the latest status of the long-running operation, handling diagnostic scope creation for distributed - /// tracing. The default scope name can be changed with the "operationTypeName" parameter passed to the constructor. - /// Usage example: - /// - /// public async ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken) => - /// await _operationInternal.UpdateStatusAsync(cancellationToken).ConfigureAwait(false); - /// - /// - /// - /// A controlling the request lifetime. - /// The HTTP response received from the server. - /// - /// After a successful run, this method will update and might update . - /// - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public async ValueTask UpdateStatusAsync(CancellationToken cancellationToken) => - await UpdateStatusAsync(async: true, cancellationToken).ConfigureAwait(false); - - /// - /// Calls the server to get the latest status of the long-running operation, handling diagnostic scope creation for distributed - /// tracing. The default scope name can be changed with the "operationTypeName" parameter passed to the constructor. - /// Usage example: - /// - /// public Response UpdateStatus(CancellationToken cancellationToken) => _operationInternal.UpdateStatus(cancellationToken); - /// - /// - /// - /// A controlling the request lifetime. - /// The HTTP response received from the server. - /// - /// After a successful run, this method will update and might update . - /// - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public Response UpdateStatus(CancellationToken cancellationToken) => - UpdateStatusAsync(async: false, cancellationToken).EnsureCompleted(); - - /// - /// Periodically calls until the long-running operation completes. - /// After each service call, a retry-after header may be returned to communicate that there is no reason to poll - /// for status change until the specified time has passed. The maximum of the retry after value and the fallback strategy - /// is then used as the wait interval. - /// Headers supported are: "Retry-After", "retry-after-ms", and "x-ms-retry-after-ms", - /// Usage example: - /// - /// public async ValueTask<Response<T>> WaitForCompletionAsync(CancellationToken cancellationToken) => - /// await _operationInternal.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - /// - /// - /// - /// A controlling the request lifetime. - /// The last HTTP response received from the server, including the final result of the long-running operation. - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public async ValueTask WaitForCompletionResponseAsync(CancellationToken cancellationToken) - => await WaitForCompletionResponseAsync(async: true, null, _waitForCompletionResponseScopeName, cancellationToken).ConfigureAwait(false); - - /// - /// Periodically calls until the long-running operation completes. The interval - /// between calls is defined by the parameter , but it can change based on information returned - /// from the server. After each service call, a retry-after header may be returned to communicate that there is no reason to poll - /// for status change until the specified time has passed. In this case, the maximum value between the - /// parameter and the retry-after header is chosen as the wait interval. Headers supported are: "Retry-After", "retry-after-ms", - /// and "x-ms-retry-after-ms". - /// Usage example: - /// - /// public async ValueTask<Response<T>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) => - /// await _operationInternal.WaitForCompletionAsync(pollingInterval, cancellationToken).ConfigureAwait(false); - /// - /// - /// - /// The interval between status requests to the server. - /// A controlling the request lifetime. - /// The last HTTP response received from the server, including the final result of the long-running operation. - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public async ValueTask WaitForCompletionResponseAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) - => await WaitForCompletionResponseAsync(async: true, pollingInterval, _waitForCompletionResponseScopeName, cancellationToken).ConfigureAwait(false); - - /// - /// Periodically calls until the long-running operation completes. - /// After each service call, a retry-after header may be returned to communicate that there is no reason to poll - /// for status change until the specified time has passed. The maximum of the retry after value and the fallback strategy - /// is then used as the wait interval. - /// Headers supported are: "Retry-After", "retry-after-ms", and "x-ms-retry-after-ms", - /// and "x-ms-retry-after-ms". - /// Usage example: - /// - /// public async ValueTask<Response<T>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) => - /// await _operationInternal.WaitForCompletionAsync(pollingInterval, cancellationToken).ConfigureAwait(false); - /// - /// - /// - /// A controlling the request lifetime. - /// The last HTTP response received from the server, including the final result of the long-running operation. - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public Response WaitForCompletionResponse(CancellationToken cancellationToken) - => WaitForCompletionResponseAsync(async: false, null, _waitForCompletionResponseScopeName, cancellationToken).EnsureCompleted(); - - /// - /// Periodically calls until the long-running operation completes. The interval - /// between calls is defined by the parameter , but it can change based on information returned - /// from the server. After each service call, a retry-after header may be returned to communicate that there is no reason to poll - /// for status change until the specified time has passed. In this case, the maximum value between the - /// parameter and the retry-after header is chosen as the wait interval. Headers supported are: "Retry-After", "retry-after-ms", - /// and "x-ms-retry-after-ms". - /// Usage example: - /// - /// public async ValueTask<Response<T>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) => - /// await _operationInternal.WaitForCompletionAsync(pollingInterval, cancellationToken).ConfigureAwait(false); - /// - /// - /// - /// The interval between status requests to the server. - /// A controlling the request lifetime. - /// The last HTTP response received from the server, including the final result of the long-running operation. - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public Response WaitForCompletionResponse(TimeSpan pollingInterval, CancellationToken cancellationToken) - => WaitForCompletionResponseAsync(async: false, pollingInterval, _waitForCompletionResponseScopeName, cancellationToken).EnsureCompleted(); - - protected async ValueTask WaitForCompletionResponseAsync(bool async, TimeSpan? pollingInterval, string scopeName, CancellationToken cancellationToken) - { - // If _responseLock has the value, lockOrValue will contain that value, and no lock is acquired. - // If _responseLock doesn't have the value, GetLockOrValueAsync will acquire the lock that will be released when lockOrValue is disposed - using var lockOrValue = await _responseLock.GetLockOrValueAsync(async, cancellationToken).ConfigureAwait(false); - if (lockOrValue.HasValue) - { - return lockOrValue.Value; - } - - using var scope = CreateScope(scopeName); - try - { - var poller = new OperationPoller(_fallbackStrategy); - var response = async - ? await poller.WaitForCompletionResponseAsync(this, pollingInterval, cancellationToken).ConfigureAwait(false) - : poller.WaitForCompletionResponse(this, pollingInterval, cancellationToken); - - lockOrValue.SetValue(response); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - protected abstract ValueTask UpdateStatusAsync(bool async, CancellationToken cancellationToken); - - protected DiagnosticScope CreateScope(string scopeName) - { - DiagnosticScope scope = _diagnostics.CreateScope(scopeName); - - if (_scopeAttributes != null) - { - foreach (KeyValuePair attribute in _scopeAttributes) - { - scope.AddAttribute(attribute.Key, attribute.Value); - } - } - - scope.Start(); - return scope; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationInternalOfT.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationInternalOfT.cs deleted file mode 100644 index c1adc58603..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationInternalOfT.cs +++ /dev/null @@ -1,431 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; - -namespace Azure.Core -{ - /// - /// A helper class used to build long-running operation instances. In order to use this helper: - /// - /// Make sure your LRO implements the interface. - /// Add a private field to your LRO, and instantiate it during construction. - /// Delegate method calls to the implementations. - /// - /// Supported members: - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// , used for - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// The final result of the long-running operation. Must match the type used in . -#pragma warning disable SA1649 // File name should match first type name - internal class OperationInternal : OperationInternalBase -#pragma warning restore SA1649 - { - private readonly IOperation _operation; - private readonly AsyncLockWithValue> _stateLock; - private Response _rawResponse; - - /// - /// Initializes a new instance of the class in a final successful state. - /// - /// The final value of . - /// The final result of the long-running operation. - public static OperationInternal Succeeded(Response rawResponse, T value) => new(OperationState.Success(rawResponse, value)); - - /// - /// Initializes a new instance of the class in a final failed state. - /// - /// The final value of . - /// The exception that will be thrown by UpdateStatusAsync. - public static OperationInternal Failed(Response rawResponse, RequestFailedException operationFailedException) => new(OperationState.Failure(rawResponse, operationFailedException)); - - /// - /// Initializes a new instance of the class. - /// - /// The long-running operation making use of this class. Passing "this" is expected. - /// Used for diagnostic scope and exception creation. This is expected to be the instance created during the construction of your main client. - /// - /// The initial value of . Usually, long-running operation objects can be instantiated in two ways: - /// - /// - /// When calling a client's "Start<OperationName>" method, a service call is made to start the operation, and an instance is returned. - /// In this case, the response received from this service call can be passed here. - /// - /// - /// When a user instantiates an directly using a public constructor, there's no previous service call. In this case, passing null is expected. - /// - /// - /// - /// - /// The type name of the long-running operation making use of this class. Used when creating diagnostic scopes. If left null, the type name will be inferred based on the - /// parameter . - /// - /// The attributes to use during diagnostic scope creation. - /// The delay strategy when Retry-After header is not present. When it is present, the longer of the two delays will be used. - /// Default is . - public OperationInternal(IOperation operation, - ClientDiagnostics clientDiagnostics, - Response rawResponse, - string? operationTypeName = null, - IEnumerable>? scopeAttributes = null, - DelayStrategy? fallbackStrategy = null) - : base(clientDiagnostics, operationTypeName ?? operation.GetType().Name, scopeAttributes, fallbackStrategy) - { - _operation = operation; - _rawResponse = rawResponse; - _stateLock = new AsyncLockWithValue>(); - } - - internal OperationInternal(OperationState finalState) - : base(finalState.RawResponse) - { - // FinalOperation represents operation that is in final state and can't be updated. - // It implements IOperation and throws exception when UpdateStateAsync is called. - _operation = new FinalOperation(); - _rawResponse = finalState.RawResponse; - _stateLock = new AsyncLockWithValue>(finalState); - } - - public override Response RawResponse => _stateLock.TryGetValue(out var state) ? state.RawResponse : _rawResponse; - - public override bool HasCompleted => _stateLock.HasValue; - - /// - /// Returns true if the long-running operation completed successfully and has produced a final result. - /// Usage example: - /// - /// public bool HasValue => _operationInternal.HasValue; - /// - /// - /// - public bool HasValue => _stateLock.TryGetValue(out var state) && state.HasSucceeded; - - /// - /// The final result of the long-running operation. - /// Usage example: - /// - /// public T Value => _operationInternal.Value; - /// - /// - /// - /// Thrown when the operation has not completed yet. - /// Thrown when the operation has completed with failures. - public T Value - { - get - { - if (_stateLock.TryGetValue(out var state)) - { - if (state.HasSucceeded) - { - return state.Value!; - } - - throw state.OperationFailedException!; - } - - throw new InvalidOperationException("The operation has not completed yet."); - } - } - /// - /// Periodically calls until the long-running operation completes. - /// After each service call, a retry-after header may be returned to communicate that there is no reason to poll - /// for status change until the specified time has passed. - /// Headers supported are: "Retry-After", "retry-after-ms", and "x-ms-retry-after-ms", - /// Usage example: - /// - /// public async ValueTask<Response<T>> WaitForCompletionAsync(CancellationToken cancellationToken) => - /// await _operationInternal.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - /// - /// - /// - /// A controlling the request lifetime. - /// The last HTTP response received from the server, including the final result of the long-running operation. - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public async ValueTask> WaitForCompletionAsync(CancellationToken cancellationToken) - => await WaitForCompletionAsync(async: true, null, cancellationToken).ConfigureAwait(false); - - /// - /// Periodically calls until the long-running operation completes. The interval - /// between calls is defined by the parameter , but it can change based on information returned - /// from the server. After each service call, a retry-after header may be returned to communicate that there is no reason to poll - /// for status change until the specified time has passed. In this case, the maximum value between the - /// parameter and the retry-after header is chosen as the wait interval. Headers supported are: "Retry-After", "retry-after-ms", - /// and "x-ms-retry-after-ms". - /// Usage example: - /// - /// public async ValueTask<Response<T>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) => - /// await _operationInternal.WaitForCompletionAsync(pollingInterval, cancellationToken).ConfigureAwait(false); - /// - /// - /// - /// The interval between status requests to the server. - /// A controlling the request lifetime. - /// The last HTTP response received from the server, including the final result of the long-running operation. - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public async ValueTask> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) - => await WaitForCompletionAsync(async: true, pollingInterval, cancellationToken).ConfigureAwait(false); - - /// - /// Periodically calls until the long-running operation completes. - /// After each service call, a retry-after header may be returned to communicate that there is no reason to poll - /// for status change until the specified time has passed. - /// Headers supported are: "Retry-After", "retry-after-ms", and "x-ms-retry-after-ms", - /// Usage example: - /// - /// public async ValueTask<Response<T>> WaitForCompletionAsync(CancellationToken cancellationToken) => - /// await _operationInternal.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - /// - /// - /// - /// A controlling the request lifetime. - /// The last HTTP response received from the server, including the final result of the long-running operation. - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public Response WaitForCompletion(CancellationToken cancellationToken) - => WaitForCompletionAsync(async: false, null, cancellationToken).EnsureCompleted(); - - /// - /// Periodically calls until the long-running operation completes. The interval - /// between calls is defined by the , which takes into account any retry-after header that is returned - /// from the server. - /// Usage example: - /// - /// public async ValueTask<Response<T>> WaitForCompletionAsync(CancellationToken cancellationToken) => - /// await _operationInternal.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - /// - /// - /// - /// The interval between status requests to the server. - /// A controlling the request lifetime. - /// The last HTTP response received from the server, including the final result of the long-running operation. - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public Response WaitForCompletion(TimeSpan pollingInterval, CancellationToken cancellationToken) - => WaitForCompletionAsync(async: false, pollingInterval, cancellationToken).EnsureCompleted(); - - private async ValueTask> WaitForCompletionAsync(bool async, TimeSpan? pollingInterval, CancellationToken cancellationToken) - { - var rawResponse = await WaitForCompletionResponseAsync(async, pollingInterval, _waitForCompletionScopeName, cancellationToken).ConfigureAwait(false); - return Response.FromValue(Value, rawResponse); - } - - protected override async ValueTask UpdateStatusAsync(bool async, CancellationToken cancellationToken) - { - // If _stateLock has the final state, lockOrValue will contain that state, and no lock is acquired. - // If _stateLock doesn't have the state, GetLockOrValueAsync will acquire the lock that will be released when lockOrValue is disposed - // While _responseLock is used for the whole WaitForCompletionResponseAsync, _stateLock is used for individual calls of UpdateStatusAsync - using var asyncLock = await _stateLock.GetLockOrValueAsync(async, cancellationToken).ConfigureAwait(false); - if (asyncLock.HasValue) - { - return GetResponseFromState(asyncLock.Value); - } - - using var scope = CreateScope(_updateStatusScopeName); - try - { - var state = await _operation.UpdateStateAsync(async, cancellationToken).ConfigureAwait(false); - if (!state.HasCompleted) - { - Interlocked.Exchange(ref _rawResponse, state.RawResponse); - return state.RawResponse; - } - - if (!state.HasSucceeded && state.OperationFailedException == null) - { - state = OperationState.Failure(state.RawResponse, new RequestFailedException(state.RawResponse)); - } - - asyncLock.SetValue(state); - return GetResponseFromState(state); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - private static Response GetResponseFromState(OperationState state) - { - if (state.HasSucceeded) - { - return state.RawResponse; - } - - throw state.OperationFailedException!; - } - - private class FinalOperation : IOperation - { - public ValueTask> UpdateStateAsync(bool async, CancellationToken cancellationToken) - => throw new NotSupportedException("The operation has already completed"); - - // Unreachable path. _operation.GetRehydrationToken() is never invoked. - public RehydrationToken GetRehydrationToken() - => throw new NotSupportedException($"Getting the rehydration token of a {nameof(FinalOperation)} is not supported"); - } - } - - /// - /// An interface used by for making service calls and updating state. It's expected that - /// your long-running operation classes implement this interface. - /// - /// The final result of the long-running operation. Must match the type used in . - internal interface IOperation - { - /// - /// Calls the service and updates the state of the long-running operation. Properties directly handled by the - /// class, such as or - /// , don't need to be updated. Operation-specific properties, such - /// as "CreateOn" or "LastModified", must be manually updated by the operation implementing this - /// method. - /// Usage example: - /// - /// async ValueTask<OperationState<T>> IOperation<T>.UpdateStateAsync(bool async, CancellationToken cancellationToken)
- /// {
- /// Response<R> response = async ? <async service call> : <sync service call>;
- /// if (<operation succeeded>) return OperationState<T>.Success(response.GetRawResponse(), <parse response>);
- /// if (<operation failed>) return OperationState<T>.Failure(response.GetRawResponse());
- /// return OperationState<T>.Pending(response.GetRawResponse());
- /// } - ///
- ///
- ///
- /// true if the call should be executed asynchronously. Otherwise, false. - /// A controlling the request lifetime. - /// - /// A structure indicating the current operation state. The structure must be instantiated by one of - /// its static methods: - /// - /// Use when the operation has completed successfully. - /// Use when the operation has completed with failures. - /// Use when the operation has not completed yet. - /// - /// - ValueTask> UpdateStateAsync(bool async, CancellationToken cancellationToken); - - /// - /// Get a token that can be used to rehydrate the operation. - /// - RehydrationToken GetRehydrationToken(); - } - - /// - /// A helper structure passed to to indicate the current operation state. This structure must be - /// instantiated by one of its static methods, depending on the operation state: - /// - /// Use when the operation has completed successfully. - /// Use when the operation has completed with failures. - /// Use when the operation has not completed yet. - /// - /// - /// The final result of the long-running operation. Must match the type used in . - internal readonly struct OperationState - { - private OperationState(Response rawResponse, bool hasCompleted, bool hasSucceeded, T? value, RequestFailedException? operationFailedException) - { - RawResponse = rawResponse; - HasCompleted = hasCompleted; - HasSucceeded = hasSucceeded; - Value = value; - OperationFailedException = operationFailedException; - } - - public Response RawResponse { get; } - - public bool HasCompleted { get; } - - public bool HasSucceeded { get; } - - public T? Value { get; } - - public RequestFailedException? OperationFailedException { get; } - - /// - /// Instantiates an indicating the operation has completed successfully. - /// - /// The HTTP response obtained during the status update. - /// The final result of the long-running operation. - /// A new instance. - /// Thrown if or is null. - public static OperationState Success(Response rawResponse, T value) - { - if (rawResponse is null) - { - throw new ArgumentNullException(nameof(rawResponse)); - } - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } - - return new OperationState(rawResponse, true, true, value, default); - } - - /// - /// Instantiates an indicating the operation has completed with failures. - /// - /// The HTTP response obtained during the status update. - /// - /// The exception to throw from UpdateStatus because of the operation failure. The same exception will be thrown when - /// is called. If left null, a default exception is created based on the - /// parameter. - /// - /// A new instance. - /// Thrown if is null. - public static OperationState Failure(Response rawResponse, RequestFailedException? operationFailedException = null) - { - if (rawResponse is null) - { - throw new ArgumentNullException(nameof(rawResponse)); - } - - return new OperationState(rawResponse, true, false, default, operationFailedException); - } - - /// - /// Instantiates an indicating the operation has not completed yet. - /// - /// The HTTP response obtained during the status update. - /// A new instance. - /// Thrown if is null. - public static OperationState Pending(Response rawResponse) - { - if (rawResponse is null) - { - throw new ArgumentNullException(nameof(rawResponse)); - } - - return new OperationState(rawResponse, false, default, default, default); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationPoller.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationPoller.cs deleted file mode 100644 index 4cbd975ebb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/OperationPoller.cs +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; - -namespace Azure.Core -{ - /// - /// Implementation of LRO polling logic. - /// - internal sealed class OperationPoller - { - private readonly DelayStrategy _delayStrategy; - - public OperationPoller(DelayStrategy? strategy = null) - { - _delayStrategy = strategy ?? new FixedDelayWithNoJitterStrategy(); - } - - public ValueTask WaitForCompletionResponseAsync(Operation operation, TimeSpan? delayHint, CancellationToken cancellationToken) - => WaitForCompletionAsync(true, operation, delayHint, cancellationToken); - - public Response WaitForCompletionResponse(Operation operation, TimeSpan? delayHint, CancellationToken cancellationToken) - => WaitForCompletionAsync(false, operation, delayHint, cancellationToken).EnsureCompleted(); - - public ValueTask WaitForCompletionResponseAsync(OperationInternalBase operation, TimeSpan? delayHint, CancellationToken cancellationToken) - => WaitForCompletionAsync(true, operation, delayHint, cancellationToken); - - public Response WaitForCompletionResponse(OperationInternalBase operation, TimeSpan? delayHint, CancellationToken cancellationToken) - => WaitForCompletionAsync(false, operation, delayHint, cancellationToken).EnsureCompleted(); - - public async ValueTask> WaitForCompletionAsync(Operation operation, TimeSpan? delayHint, CancellationToken cancellationToken) where T : notnull - { - Response response = await WaitForCompletionAsync(true, operation, delayHint, cancellationToken).ConfigureAwait(false); - return Response.FromValue(operation.Value, response); - } - - public Response WaitForCompletion(Operation operation, TimeSpan? delayHint, CancellationToken cancellationToken) where T : notnull - { - Response response = WaitForCompletionAsync(false, operation, delayHint, cancellationToken).EnsureCompleted(); - return Response.FromValue(operation.Value, response); - } - - public async ValueTask> WaitForCompletionAsync(OperationInternal operation, TimeSpan? delayHint, CancellationToken cancellationToken) where T : notnull - { - Response response = await WaitForCompletionAsync(true, operation, delayHint, cancellationToken).ConfigureAwait(false); - return Response.FromValue(operation.Value, response); - } - - public Response WaitForCompletion(OperationInternal operation, TimeSpan? delayHint, CancellationToken cancellationToken) where T : notnull - { - Response response = WaitForCompletionAsync(false, operation, delayHint, cancellationToken).EnsureCompleted(); - return Response.FromValue(operation.Value, response); - } - - private async ValueTask WaitForCompletionAsync(bool async, Operation operation, TimeSpan? delayHint, CancellationToken cancellationToken) - { - int retryNumber = 0; - while (true) - { - Response response = async ? await operation.UpdateStatusAsync(cancellationToken).ConfigureAwait(false) : operation.UpdateStatus(cancellationToken); - if (operation.HasCompleted) - { - return operation.GetRawResponse(); - } - - var strategy = delayHint.HasValue ? new FixedDelayWithNoJitterStrategy(delayHint.Value) : _delayStrategy; - - await Delay(async, strategy.GetNextDelay(response, ++retryNumber), cancellationToken).ConfigureAwait(false); - } - } - - private async ValueTask WaitForCompletionAsync(bool async, OperationInternalBase operation, TimeSpan? delayHint, CancellationToken cancellationToken) - { - int retryNumber = 0; - while (true) - { - Response response = async ? await operation.UpdateStatusAsync(cancellationToken).ConfigureAwait(false) : operation.UpdateStatus(cancellationToken); - if (operation.HasCompleted) - { - return operation.RawResponse; - } - - var strategy = delayHint.HasValue ? new FixedDelayWithNoJitterStrategy(delayHint.Value) : _delayStrategy; - - await Delay(async, strategy.GetNextDelay(response, ++retryNumber), cancellationToken).ConfigureAwait(false); - } - } - - private static async ValueTask Delay(bool async, TimeSpan delay, CancellationToken cancellationToken) - { - if (async) - { - await Task.Delay(delay, cancellationToken).ConfigureAwait(false); - } - else if (cancellationToken.CanBeCanceled) - { - if (cancellationToken.WaitHandle.WaitOne(delay)) - { - cancellationToken.ThrowIfCancellationRequested(); - } - } - else - { - Thread.Sleep(delay); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/Page.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/Page.cs deleted file mode 100644 index 1438fdfd5f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/Page.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System.Collections.Generic; -using System.Linq; - -namespace Azure.Core -{ - internal static class Page - { - public static Page FromValues(IEnumerable values, string continuationToken, Response response) => - Page.FromValues(values.ToList(), continuationToken, response); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/PageableHelpers.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/PageableHelpers.cs deleted file mode 100644 index 4d15951fef..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/PageableHelpers.cs +++ /dev/null @@ -1,556 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Text; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; - -namespace Azure.Core -{ - internal static class PageableHelpers - { - private static readonly byte[] DefaultItemPropertyName = Encoding.UTF8.GetBytes("value"); - private static readonly byte[] DefaultNextLinkPropertyName = Encoding.UTF8.GetBytes("nextLink"); - - public static AsyncPageable CreateAsyncPageable(Func? createFirstPageRequest, Func? createNextPageRequest, Func? Values, string? NextLink)> responseParser, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string scopeName, RequestContext? requestContext = null) where T : notnull - { - return new AsyncPageableWrapper(new PageableImplementation(createFirstPageRequest, createNextPageRequest, responseParser, pipeline, clientDiagnostics, scopeName, null, requestContext)); - } - - public static AsyncPageable CreateAsyncPageable(Func? createFirstPageRequest, Func? createNextPageRequest, Func valueFactory, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string scopeName, string? itemPropertyName, string? nextLinkPropertyName, CancellationToken cancellationToken) where T : notnull - { - return new AsyncPageableWrapper(new PageableImplementation(null, createFirstPageRequest, createNextPageRequest, valueFactory, pipeline, clientDiagnostics, scopeName, itemPropertyName, nextLinkPropertyName, null, cancellationToken, null)); - } - - public static AsyncPageable CreateAsyncPageable(Func? createFirstPageRequest, Func? createNextPageRequest, Func valueFactory, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string scopeName, string? itemPropertyName, string? nextLinkPropertyName, RequestContext? requestContext = null) where T : notnull - { - return new AsyncPageableWrapper(new PageableImplementation(null, createFirstPageRequest, createNextPageRequest, valueFactory, pipeline, clientDiagnostics, scopeName, itemPropertyName, nextLinkPropertyName, null, requestContext?.CancellationToken, requestContext?.ErrorOptions)); - } - - public static AsyncPageable CreateAsyncPageable(Response initialResponse, Func? createNextPageRequest, Func valueFactory, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string scopeName, string? itemPropertyName, string? nextLinkPropertyName, CancellationToken cancellationToken) where T : notnull - { - return new AsyncPageableWrapper(new PageableImplementation(initialResponse, null, createNextPageRequest, valueFactory, pipeline, clientDiagnostics, scopeName, itemPropertyName, nextLinkPropertyName, null, cancellationToken, null)); - } - - public static Pageable CreatePageable(Func? createFirstPageRequest, Func? createNextPageRequest, Func? Values, string? NextLink)> responseParser, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string scopeName, RequestContext? requestContext = null) where T : notnull - { - return new PageableWrapper(new PageableImplementation(createFirstPageRequest, createNextPageRequest, responseParser, pipeline, clientDiagnostics, scopeName, null, requestContext)); - } - - public static Pageable CreatePageable(Func? createFirstPageRequest, Func? createNextPageRequest, Func valueFactory, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string scopeName, string? itemPropertyName, string? nextLinkPropertyName, CancellationToken cancellationToken) where T : notnull - { - return new PageableWrapper(new PageableImplementation(null, createFirstPageRequest, createNextPageRequest, valueFactory, pipeline, clientDiagnostics, scopeName, itemPropertyName, nextLinkPropertyName, null, cancellationToken, null)); - } - - public static Pageable CreatePageable(Func? createFirstPageRequest, Func? createNextPageRequest, Func valueFactory, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string scopeName, string? itemPropertyName, string? nextLinkPropertyName, RequestContext? requestContext = null) where T : notnull - { - return new PageableWrapper(new PageableImplementation(null, createFirstPageRequest, createNextPageRequest, valueFactory, pipeline, clientDiagnostics, scopeName, itemPropertyName, nextLinkPropertyName, null, requestContext?.CancellationToken, requestContext?.ErrorOptions)); - } - - public static Pageable CreatePageable(Response initialResponse, Func? createNextPageRequest, Func valueFactory, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string scopeName, string? itemPropertyName, string? nextLinkPropertyName, CancellationToken cancellationToken) where T : notnull - { - return new PageableWrapper(new PageableImplementation(initialResponse, null, createNextPageRequest, valueFactory, pipeline, clientDiagnostics, scopeName, itemPropertyName, nextLinkPropertyName, null, cancellationToken, null)); - } - - public static async ValueTask>> CreateAsyncPageable(WaitUntil waitUntil, HttpMessage message, Func? createNextPageMethod, Func valueFactory, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, OperationFinalStateVia finalStateVia, string scopeName, string? itemPropertyName, string? nextLinkPropertyName, RequestContext? requestContext = null) where T : notnull - { - AsyncPageable ResultSelector(Response r) => new AsyncPageableWrapper(new PageableImplementation(r, null, createNextPageMethod, valueFactory, pipeline, clientDiagnostics, scopeName, itemPropertyName, nextLinkPropertyName, null, requestContext?.CancellationToken, requestContext?.ErrorOptions)); - - var response = await pipeline.ProcessMessageAsync(message, requestContext).ConfigureAwait(false); - var operation = new ProtocolOperation>(clientDiagnostics, pipeline, message.Request, response, finalStateVia, scopeName, ResultSelector); - if (waitUntil == WaitUntil.Completed) - { - await operation.WaitForCompletionAsync(requestContext?.CancellationToken ?? default).ConfigureAwait(false); - } - return operation; - } - - public static Operation> CreatePageable(WaitUntil waitUntil, HttpMessage message, Func? createNextPageMethod, Func valueFactory, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, OperationFinalStateVia finalStateVia, string scopeName, string? itemPropertyName, string? nextLinkPropertyName, RequestContext? requestContext = null) where T : notnull - { - Pageable ResultSelector(Response r) => new PageableWrapper(new PageableImplementation(r, null, createNextPageMethod, valueFactory, pipeline, clientDiagnostics, scopeName, itemPropertyName, nextLinkPropertyName, null, requestContext?.CancellationToken, requestContext?.ErrorOptions)); - - var response = pipeline.ProcessMessage(message, requestContext); - var operation = new ProtocolOperation>(clientDiagnostics, pipeline, message.Request, response, finalStateVia, scopeName, ResultSelector); - if (waitUntil == WaitUntil.Completed) - { - operation.WaitForCompletion(requestContext?.CancellationToken ?? default); - } - return operation; - } - - public static Pageable CreateEnumerable(Func> firstPageFunc, Func>? nextPageFunc, int? pageSize = default) where T : notnull - { - Func> first = (_, pageSizeHint) => firstPageFunc(pageSizeHint); - return new FuncPageable(first, nextPageFunc, pageSize); - } - - public static AsyncPageable CreateAsyncEnumerable(Func>> firstPageFunc, Func>>? nextPageFunc, int? pageSize = default) where T : notnull - { - Func>> first = (_, pageSizeHint) => firstPageFunc(pageSizeHint); - return new FuncAsyncPageable(first, nextPageFunc, pageSize); - } - - internal class FuncAsyncPageable : AsyncPageable where T : notnull - { - private readonly Func>> _firstPageFunc; - private readonly Func>>? _nextPageFunc; - private readonly int? _defaultPageSize; - - public FuncAsyncPageable(Func>> firstPageFunc, Func>>? nextPageFunc, int? defaultPageSize = default) - { - _firstPageFunc = firstPageFunc; - _nextPageFunc = nextPageFunc; - _defaultPageSize = defaultPageSize; - } - - public override async IAsyncEnumerable> AsPages(string? continuationToken = default, int? pageSizeHint = default) - { - Func>>? pageFunc = string.IsNullOrEmpty(continuationToken) ? _firstPageFunc : _nextPageFunc; - - if (pageFunc == null) - { - yield break; - } - - int? pageSize = pageSizeHint ?? _defaultPageSize; - do - { - Page pageResponse = await pageFunc(continuationToken, pageSize).ConfigureAwait(false); - yield return pageResponse; - continuationToken = pageResponse.ContinuationToken; - pageFunc = _nextPageFunc; - } while (!string.IsNullOrEmpty(continuationToken) && pageFunc != null); - } - } - - internal class FuncPageable : Pageable where T : notnull - { - private readonly Func> _firstPageFunc; - private readonly Func>? _nextPageFunc; - private readonly int? _defaultPageSize; - - public FuncPageable(Func> firstPageFunc, Func>? nextPageFunc, int? defaultPageSize = default) - { - _firstPageFunc = firstPageFunc; - _nextPageFunc = nextPageFunc; - _defaultPageSize = defaultPageSize; - } - - public override IEnumerable> AsPages(string? continuationToken = default, int? pageSizeHint = default) - { - Func>? pageFunc = string.IsNullOrEmpty(continuationToken) ? _firstPageFunc : _nextPageFunc; - - if (pageFunc == null) - { - yield break; - } - - int? pageSize = pageSizeHint ?? _defaultPageSize; - do - { - Page pageResponse = pageFunc(continuationToken, pageSize); - yield return pageResponse; - continuationToken = pageResponse.ContinuationToken; - pageFunc = _nextPageFunc; - } while (!string.IsNullOrEmpty(continuationToken) && pageFunc != null); - } - } - - internal class AsyncPageableWrapper : AsyncPageable where T : notnull - { - private readonly PageableImplementation _implementation; - - public AsyncPageableWrapper(PageableImplementation implementation) - { - _implementation = implementation; - } - - public override IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) => _implementation.GetAsyncEnumerator(cancellationToken); - public override IAsyncEnumerable> AsPages(string? continuationToken = null, int? pageSizeHint = null) => _implementation.AsPagesAsync(continuationToken, pageSizeHint, default); - } - - internal class PageableWrapper : Pageable where T : notnull - { - private readonly PageableImplementation _implementation; - - public PageableWrapper(PageableImplementation implementation) - { - _implementation = implementation; - } - - public override IEnumerator GetEnumerator() => _implementation.GetEnumerator(); - public override IEnumerable> AsPages(string? continuationToken = null, int? pageSizeHint = null) => _implementation.AsPages(continuationToken, pageSizeHint); - } - - internal class PageableImplementation - { - private readonly Response? _initialResponse; - private readonly Func? _createFirstPageRequest; - private readonly Func? _createNextPageRequest; - private readonly HttpPipeline _pipeline; - private readonly ClientDiagnostics _clientDiagnostics; - private readonly Func? _valueFactory; - private readonly Func? Values, string? NextLink)>? _responseParser; - private readonly string _scopeName; - private readonly byte[] _itemPropertyName; - private readonly byte[] _nextLinkPropertyName; - private readonly int? _defaultPageSize; - private readonly CancellationToken _cancellationToken; - private readonly ErrorOptions? _errorOptions; - - public PageableImplementation( - Response? initialResponse, - Func? createFirstPageRequest, - Func? createNextPageRequest, - Func valueFactory, - HttpPipeline pipeline, - ClientDiagnostics clientDiagnostics, - string scopeName, - string? itemPropertyName, - string? nextLinkPropertyName, - int? defaultPageSize, - CancellationToken? cancellationToken, - ErrorOptions? errorOptions) - { - _initialResponse = initialResponse; - _createFirstPageRequest = createFirstPageRequest; - _createNextPageRequest = createNextPageRequest; - _valueFactory = typeof(T) == typeof(BinaryData) ? null : valueFactory; - _responseParser = null; - _pipeline = pipeline; - _clientDiagnostics = clientDiagnostics; - _scopeName = scopeName; - _itemPropertyName = itemPropertyName != null ? Encoding.UTF8.GetBytes(itemPropertyName) : DefaultItemPropertyName; - _nextLinkPropertyName = nextLinkPropertyName != null ? Encoding.UTF8.GetBytes(nextLinkPropertyName) : DefaultNextLinkPropertyName; - _defaultPageSize = defaultPageSize; - _cancellationToken = cancellationToken ?? default; - _errorOptions = errorOptions ?? ErrorOptions.Default; - } - - public PageableImplementation(Func? createFirstPageRequest, Func? createNextPageRequest, Func? Values, string? NextLink)> responseParser, HttpPipeline pipeline, ClientDiagnostics clientDiagnostics, string scopeName, int? defaultPageSize, RequestContext? requestContext) - { - _createFirstPageRequest = createFirstPageRequest; - _createNextPageRequest = createNextPageRequest; - _valueFactory = null; - _responseParser = responseParser; - _pipeline = pipeline; - _clientDiagnostics = clientDiagnostics; - _scopeName = scopeName; - _itemPropertyName = Array.Empty(); - _nextLinkPropertyName = Array.Empty(); - _defaultPageSize = defaultPageSize; - _cancellationToken = requestContext?.CancellationToken ?? default; - _errorOptions = requestContext?.ErrorOptions ?? ErrorOptions.Default; - } - - public async IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) - { - string? nextLink = null; - do - { - var response = await GetNextResponseAsync(null, nextLink, cancellationToken).ConfigureAwait(false); - if (!TryGetItemsFromResponse(response, out nextLink, out var jsonArray, out var items)) - { - continue; - } - - if (_valueFactory != null) - { - foreach (var jsonItem in jsonArray) - { - yield return _valueFactory(jsonItem); - } - } - else - { - foreach (var item in items!) - { - yield return item; - } - } - } while (!string.IsNullOrEmpty(nextLink)); - } - - public async IAsyncEnumerable> AsPagesAsync(string? continuationToken, int? pageSizeHint, [EnumeratorCancellation] CancellationToken cancellationToken) - { - string? nextLink = continuationToken; - do - { - var response = await GetNextResponseAsync(pageSizeHint, nextLink, cancellationToken).ConfigureAwait(false); - if (response is null) - { - yield break; - } - yield return CreatePage(response, out nextLink); - } while (!string.IsNullOrEmpty(nextLink)); - } - - public IEnumerator GetEnumerator() - { - string? nextLink = null; - do - { - var response = GetNextResponse(null, nextLink); - if (!TryGetItemsFromResponse(response, out nextLink, out var jsonArray, out var items)) - { - continue; - } - - if (_valueFactory != null) - { - foreach (var jsonItem in jsonArray) - { - yield return _valueFactory(jsonItem); - } - } - else - { - foreach (var item in items!) - { - yield return item; - } - } - } while (!string.IsNullOrEmpty(nextLink)); - } - - public IEnumerable> AsPages(string? continuationToken, int? pageSizeHint) - { - string? nextLink = continuationToken; - do - { - var response = GetNextResponse(pageSizeHint, nextLink); - if (response is null) - { - yield break; - } - yield return CreatePage(response, out nextLink); - } while (!string.IsNullOrEmpty(nextLink)); - } - - private Response? GetNextResponse(int? pageSizeHint, string? nextLink) - { - var message = CreateMessage(pageSizeHint, nextLink, out var response); - if (message == null) - { - return response; - } - - using DiagnosticScope scope = _clientDiagnostics.CreateScope(_scopeName); - scope.Start(); - try - { - _pipeline.Send(message, _cancellationToken); - return GetResponse(message); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - private async ValueTask GetNextResponseAsync(int? pageSizeHint, string? nextLink, CancellationToken cancellationToken) - { - var message = CreateMessage(pageSizeHint, nextLink, out var response); - if (message == null) - { - return response; - } - - using DiagnosticScope scope = _clientDiagnostics.CreateScope(_scopeName); - scope.Start(); - try - { - if (cancellationToken.CanBeCanceled && _cancellationToken.CanBeCanceled) - { - using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cancellationToken); - await _pipeline.SendAsync(message, cts.Token).ConfigureAwait(false); - } - else - { - var ct = cancellationToken.CanBeCanceled ? cancellationToken : _cancellationToken; - await _pipeline.SendAsync(message, ct).ConfigureAwait(false); - } - - return GetResponse(message); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - private HttpMessage? CreateMessage(int? pageSizeHint, string? nextLink, out Response? response) - { - if (!string.IsNullOrEmpty(nextLink)) - { - response = null; - return _createNextPageRequest?.Invoke(pageSizeHint ?? _defaultPageSize, nextLink!); - } - - if (_createFirstPageRequest == null) - { - response = _initialResponse; - return null; - } - - response = null; - return _createFirstPageRequest(pageSizeHint ?? _defaultPageSize); - } - - private Response GetResponse(HttpMessage message) - { - if (message.Response.IsError && _errorOptions != ErrorOptions.NoThrow) - { - throw new RequestFailedException(message.Response); - } - - return message.Response; - } - - // Tries to parse response either using default logic or by using custom parser - // Returns true when either jsonArrayEnumerator is not default or items is not null - private bool TryGetItemsFromResponse(Response? response, out string? nextLink, out JsonElement.ArrayEnumerator jsonArrayEnumerator, out List? items) - { - if (response is null) - { - nextLink = default; - jsonArrayEnumerator = default; - items = default; - return false; - } - - if (_valueFactory is not null) - { - items = default; - var document = response.ContentStream != null ? JsonDocument.Parse(response.ContentStream) : JsonDocument.Parse(response.Content); - if (_createNextPageRequest is null && _itemPropertyName.Length == 0) // Pageable is a simple collection of elements - { - nextLink = null; - jsonArrayEnumerator = document.RootElement.EnumerateArray(); - return true; - } - - nextLink = document.RootElement.TryGetProperty(_nextLinkPropertyName, out var nextLinkValue) ? nextLinkValue.GetString() : null; - if (document.RootElement.TryGetProperty(_itemPropertyName, out var itemsValue)) - { - jsonArrayEnumerator = itemsValue.EnumerateArray(); - return true; - } - - jsonArrayEnumerator = default; - return false; - } - - jsonArrayEnumerator = default; - // _responseParser will be null when T is BinaryData - var parsedResponse = _responseParser?.Invoke(response) ?? ParseResponseForBinaryData(response, _itemPropertyName, _nextLinkPropertyName); - items = parsedResponse.Values; - nextLink = parsedResponse.NextLink; - return items is not null; - } - - private Page CreatePage(Response response, out string? nextLink) - { - if (!TryGetItemsFromResponse(response, out nextLink, out var jsonArray, out var items)) - { - return Page.FromValues(Array.Empty(), nextLink, response); - } - - if (_valueFactory == null) - { - return Page.FromValues(items!, nextLink, response); - } - - var values = new List(); - foreach (var jsonItem in jsonArray) - { - values.Add(_valueFactory(jsonItem)); - } - - return Page.FromValues(values, nextLink, response); - } - } - - // This method is used to avoid calling _valueFactory for BinaryData cause it requires instantiation of strings. - // Remove it when `JsonElement` provides access to its UTF8 buffer. - // See also PageableMethodsWriterExtensions.GetValueFactory - private static (List? Values, string? NextLink) ParseResponseForBinaryData(Response response, byte[] itemPropertyName, byte[] nextLinkPropertyName) - { - var content = response.Content.ToMemory(); - var r = new Utf8JsonReader(content.Span); - - List? items = null; - string? nextLink = null; - - if (!r.Read() || r.TokenType != JsonTokenType.StartObject) - { - throw new InvalidOperationException("Expected response to be JSON object"); - } - - while (r.Read()) - { - switch (r.TokenType) - { - case JsonTokenType.PropertyName: - if (r.ValueTextEquals(nextLinkPropertyName)) - { - r.Read(); - nextLink = r.GetString(); - } - else if (r.ValueTextEquals(itemPropertyName)) - { - if (!r.Read() || r.TokenType != JsonTokenType.StartArray) - { - throw new InvalidOperationException($"Expected {Encoding.UTF8.GetString(itemPropertyName)} to be an array"); - } - - while (r.Read() && r.TokenType != JsonTokenType.EndArray) - { - var element = ReadBinaryData(ref r, content); - items ??= new List(); - items.Add((T)element); - } - } - else - { - r.Skip(); - } - break; - case JsonTokenType.EndObject: - break; - - default: - throw new Exception("Unexpected token"); - } - } - - return (items, nextLink); - - static object ReadBinaryData(ref Utf8JsonReader r, in ReadOnlyMemory content) - { - switch (r.TokenType) - { - case JsonTokenType.StartObject or JsonTokenType.StartArray: - int elementStart = (int)r.TokenStartIndex; - r.Skip(); - int elementEnd = (int)r.TokenStartIndex; - int length = elementEnd - elementStart + 1; - return new BinaryData(content.Slice(elementStart, length)); - case JsonTokenType.String: - return new BinaryData(content.Slice((int)r.TokenStartIndex, r.ValueSpan.Length + 2 /* open and closing quotes are not captured in the value span */)); - default: - return new BinaryData(content.Slice((int)r.TokenStartIndex, r.ValueSpan.Length)); - } - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/PropertyReferenceTypeAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/PropertyReferenceTypeAttribute.cs deleted file mode 100644 index 141b350a5e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/PropertyReferenceTypeAttribute.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -namespace Azure.Core -{ - /// - /// An attribute class indicating to Autorest a reference type for code generation. - /// - [AttributeUsage(AttributeTargets.Class)] - internal class PropertyReferenceTypeAttribute : Attribute - { - /// - /// Instantiate a new reference type attribute. - /// - /// An array of property names that are optional when comparing the type. - public PropertyReferenceTypeAttribute(string[] optionalProperties) - : this(optionalProperties, Array.Empty()) - { - } - - /// - /// Instantiate a new reference type attribute. - /// - /// An array of property names that are optional when comparing the type. - /// An array of internal properties to include for the reference type when evaluating whether type - /// replacement should occur. When evaluating a type for replacement with a reference type, all internal properties are considered on the - /// type to be replaced. Thus this parameter can be used to specify internal properties to allow replacement to occur on a type with internal - /// properties. - public PropertyReferenceTypeAttribute(string[] optionalProperties, string[] internalPropertiesToInclude) - { - OptionalProperties = optionalProperties; - InternalPropertiesToInclude = internalPropertiesToInclude; - } - - public string[] InternalPropertiesToInclude { get; } - - /// - /// Instantiate a new reference type attribute. - /// - public PropertyReferenceTypeAttribute() - : this(Array.Empty(), Array.Empty()) - { - } - - /// - /// Get an array of property names that are optional when comparing the type. - /// - public string[] OptionalProperties { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ProtocolOperation.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ProtocolOperation.cs deleted file mode 100644 index ce76a07848..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ProtocolOperation.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; - -namespace Azure.Core -{ - internal class ProtocolOperation : Operation, IOperation where T : notnull - { - private readonly Func _resultSelector; - private readonly OperationInternal _operation; - private readonly IOperation _nextLinkOperation; - - internal ProtocolOperation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response, OperationFinalStateVia finalStateVia, string scopeName, Func resultSelector) - { - _resultSelector = resultSelector; - _nextLinkOperation = NextLinkOperationImplementation.Create(pipeline, request.Method, request.Uri.ToUri(), response, finalStateVia); - _operation = new OperationInternal(this, clientDiagnostics, response, scopeName); - } - -#pragma warning disable CA1822 - // This scenario is currently unsupported. - // See: https://github.com/Azure/autorest.csharp/issues/2158. - /// - public override string Id => throw new NotSupportedException(); -#pragma warning restore CA1822 - - /// - public override RehydrationToken? GetRehydrationToken() => ((IOperation)this).GetRehydrationToken(); - - RehydrationToken IOperation.GetRehydrationToken() => _nextLinkOperation.GetRehydrationToken(); - - /// - public override T Value => _operation.Value; - - /// - public override bool HasCompleted => _operation.HasCompleted; - - /// - public override bool HasValue => _operation.HasValue; - - /// - public override Response GetRawResponse() => _operation.RawResponse; - - /// - public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); - - /// - public override ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); - - /// - public override ValueTask> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken); - - /// - public override ValueTask> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken); - - async ValueTask> IOperation.UpdateStateAsync(bool async, CancellationToken cancellationToken) - { - var state = await _nextLinkOperation.UpdateStateAsync(async, cancellationToken).ConfigureAwait(false); - if (state.HasSucceeded) - { - return OperationState.Success(state.RawResponse, _resultSelector(state.RawResponse)); - } - - if (state.HasCompleted) - { - return OperationState.Failure(state.RawResponse, state.OperationFailedException); - } - - return OperationState.Pending(state.RawResponse); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/RawRequestUriBuilder.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/RawRequestUriBuilder.cs deleted file mode 100644 index f48b1f6ed6..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/RawRequestUriBuilder.cs +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; - -namespace Azure.Core -{ - internal class RawRequestUriBuilder: RequestUriBuilder - { - private const string SchemeSeparator = "://"; - private const char HostSeparator = '/'; - private const char PortSeparator = ':'; - private static readonly char[] HostOrPort = { HostSeparator, PortSeparator }; - private const char QueryBeginSeparator = '?'; - private const char QueryContinueSeparator = '&'; - private const char QueryValueSeparator = '='; - - private RawWritingPosition? _position; - - private static void GetQueryParts(ReadOnlySpan queryUnparsed, out ReadOnlySpan name, out ReadOnlySpan value) - { - int separatorIndex = queryUnparsed.IndexOf(QueryValueSeparator); - if (separatorIndex == -1) - { - name = queryUnparsed; - value = ReadOnlySpan.Empty; - } - else - { - name = queryUnparsed.Slice(0, separatorIndex); - value = queryUnparsed.Slice(separatorIndex + 1); - } - } - - public void AppendRaw(string value, bool escape) - { - AppendRaw(value.AsSpan(), escape); - } - - private void AppendRaw(ReadOnlySpan value, bool escape) - { - if (_position == null) - { - if (HasQuery) - { - _position = RawWritingPosition.Query; - } - else if (HasPath) - { - _position = RawWritingPosition.Path; - } - else if (!string.IsNullOrEmpty(Host)) - { - _position = RawWritingPosition.Host; - } - else - { - _position = RawWritingPosition.Scheme; - } - } - - while (!value.IsEmpty) - { - if (_position == RawWritingPosition.Scheme) - { - int separator = value.IndexOf(SchemeSeparator.AsSpan(), StringComparison.InvariantCultureIgnoreCase); - if (separator == -1) - { - Scheme += value.ToString(); - value = ReadOnlySpan.Empty; - } - else - { - Scheme += value.Slice(0, separator).ToString(); - // TODO: Find a better way to map schemes to default ports - Port = string.Equals(Scheme, "https", StringComparison.OrdinalIgnoreCase) ? 443 : 80; - value = value.Slice(separator + SchemeSeparator.Length); - _position = RawWritingPosition.Host; - } - } - else if (_position == RawWritingPosition.Host) - { - int separator = value.IndexOfAny(HostOrPort); - if (separator == -1) - { - if (!HasPath) - { - Host += value.ToString(); - value = ReadOnlySpan.Empty; - } - else - { - // All Host information must be written before Path information - // If Path already has information, we transition to writing Path - _position = RawWritingPosition.Path; - } - } - else - { - Host += value.Slice(0, separator).ToString(); - _position = value[separator] == HostSeparator ? RawWritingPosition.Path : RawWritingPosition.Port; - value = value.Slice(separator + 1); - } - } - else if (_position == RawWritingPosition.Port) - { - int separator = value.IndexOf(HostSeparator); - if (separator == -1) - { -#if NETCOREAPP2_1_OR_GREATER - Port = int.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture); -#else - Port = int.Parse(value.ToString(), CultureInfo.InvariantCulture); -#endif - value = ReadOnlySpan.Empty; - } - else - { -#if NETCOREAPP2_1_OR_GREATER - Port = int.Parse(value.Slice(0, separator), NumberStyles.Integer, CultureInfo.InvariantCulture); -#else - Port = int.Parse(value.Slice(0, separator).ToString(), CultureInfo.InvariantCulture); -#endif - value = value.Slice(separator + 1); - } - // Port cannot be split (like Host), so always transition to Path when Port is parsed - _position = RawWritingPosition.Path; - } - else if (_position == RawWritingPosition.Path) - { - int separator = value.IndexOf(QueryBeginSeparator); - if (separator == -1) - { - AppendPath(value, escape); - value = ReadOnlySpan.Empty; - } - else - { - AppendPath(value.Slice(0, separator), escape); - value = value.Slice(separator + 1); - _position = RawWritingPosition.Query; - } - } - else if (_position == RawWritingPosition.Query) - { - int separator = value.IndexOf(QueryContinueSeparator); - if (separator == 0) - { - value = value.Slice(1); - } - else if (separator == -1) - { - GetQueryParts(value, out var queryName, out var queryValue); - AppendQuery(queryName, queryValue, escape); - value = ReadOnlySpan.Empty; - } - else - { - GetQueryParts(value.Slice(0, separator), out var queryName, out var queryValue); - AppendQuery(queryName, queryValue, escape); - value = value.Slice(separator + 1); - } - } - } - } - - private enum RawWritingPosition - { - Scheme, - Host, - Port, - Path, - Query - } - - public void AppendRawNextLink(string nextLink, bool escape) - { - // If it is an absolute link, we use the nextLink as the entire url - if (nextLink.StartsWith(Uri.UriSchemeHttp, StringComparison.InvariantCultureIgnoreCase)) - { - Reset(new Uri(nextLink)); - return; - } - - AppendRaw(nextLink, escape); - } - - public void AppendQuery(string name, bool value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, float value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, DateTimeOffset value, string format, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value, format), escape); - - public void AppendQuery(string name, TimeSpan value, string format, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value, format), escape); - - public void AppendQuery(string name, double value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, decimal value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, int value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, long value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, TimeSpan value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, byte[] value, string format, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value, format), escape); - - public void AppendQuery(string name, Guid value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQueryDelimited(string name, IEnumerable value, string delimiter, string? format = null, bool escape = true) - { - delimiter ??= ","; - IEnumerable stringValues = value.Select(v => TypeFormatters.ConvertToString(v, format)); - AppendQuery(name, string.Join(delimiter, stringValues), escape); - } - - public void AppendPathDelimited(IEnumerable value, string delimiter, string? format = null, bool escape = true) - { - delimiter ??= ","; - IEnumerable stringValues = value.Select(v => TypeFormatters.ConvertToString(v, format)); - AppendPath(string.Join(delimiter, stringValues), escape); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ReferenceTypeAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ReferenceTypeAttribute.cs deleted file mode 100644 index 04e86cc394..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ReferenceTypeAttribute.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -namespace Azure.Core -{ - /// - /// An attribute class indicating to Autorest a reference type for code generation. - /// - [AttributeUsage(AttributeTargets.Class)] - internal class ReferenceTypeAttribute : Attribute - { - /// - /// Instantiate a new reference type attribute. - /// - /// An array of property names that are optional when comparing the type. - public ReferenceTypeAttribute(string[] optionalProperties) - { - OptionalProperties = optionalProperties; - } - - /// - /// Instantiate a new reference type attribute. - /// - public ReferenceTypeAttribute() - : this(Array.Empty()) - { - } - - /// - /// Get an array of property names that are optional when comparing the type. - /// - public string[] OptionalProperties { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ResponseErrorConverter.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ResponseErrorConverter.cs deleted file mode 100644 index 60de2e908d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/ResponseErrorConverter.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace Azure.ResourceManager -{ - /// - /// A custom for that can be used - /// with the System.Text.Json source generator, since the built-in converter on - /// is internal and inaccessible to source generation. - /// - internal sealed class ResponseErrorConverter : JsonConverter - { - public override ResponseError? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return ReadResponseError(document.RootElement); - } - - public override void Write(Utf8JsonWriter writer, ResponseError value, JsonSerializerOptions options) - { - if (value is null) - { - writer.WriteNullValue(); - return; - } - - writer.WriteStartObject(); - - if (value.Code is not null) - { - writer.WriteString("code"u8, value.Code); - } - - if (value.Message is not null) - { - writer.WriteString("message"u8, value.Message); - } - - writer.WriteEndObject(); - } - - private static ResponseError? ReadResponseError(JsonElement element) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - - string? code = null; - if (element.TryGetProperty("code", out var property)) - { - code = property.GetString(); - } - - string? message = null; - if (element.TryGetProperty("message", out property)) - { - message = property.GetString(); - } - - return new ResponseError(code, message); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/SequentialDelayStrategy.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/SequentialDelayStrategy.cs deleted file mode 100644 index 5185fa1201..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/SequentialDelayStrategy.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -#nullable enable - -namespace Azure.Core -{ - /// - /// A delay strategy that uses a fixed sequence of delays with no jitter applied. This is used by management LROs. - /// - internal class SequentialDelayStrategy : DelayStrategy - { - private static readonly TimeSpan[] _pollingSequence = new TimeSpan[] - { - TimeSpan.FromSeconds(1), - TimeSpan.FromSeconds(1), - TimeSpan.FromSeconds(1), - TimeSpan.FromSeconds(2), - TimeSpan.FromSeconds(4), - TimeSpan.FromSeconds(8), - TimeSpan.FromSeconds(16), - TimeSpan.FromSeconds(32) - }; - private static readonly TimeSpan _maxDelay = _pollingSequence[_pollingSequence.Length - 1]; - - public SequentialDelayStrategy() : base(_maxDelay, 0) - { - } - - protected override TimeSpan GetNextDelayCore(Response? response, int retryNumber) - { - int index = retryNumber - 1; - return index >= _pollingSequence.Length ? _maxDelay : _pollingSequence[index]; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/SerializationConstructorAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/SerializationConstructorAttribute.cs deleted file mode 100644 index fbe9465541..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/SerializationConstructorAttribute.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -namespace Azure.Core -{ - /// - /// An attribute class indicating to AutoRest which constructor to use for serialization. - /// - [AttributeUsage(AttributeTargets.Constructor)] - internal class SerializationConstructorAttribute : Attribute - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/SharedExtensions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/SharedExtensions.cs deleted file mode 100644 index 215fd316e5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/SharedExtensions.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; - -namespace Azure.ResourceManager -{ - /// - /// helper class - /// - internal static class SharedExtensions - { - /// - /// Collects the segments in a resource identifier into a string - /// - /// the resource identifier - /// - public static string SubstringAfterProviderNamespace(this ResourceIdentifier resourceId) - { - const string providersKey = "/providers/"; - var rawId = resourceId.ToString(); - var indexOfProviders = rawId.LastIndexOf(providersKey, StringComparison.InvariantCultureIgnoreCase); - if (indexOfProviders < 0) - return string.Empty; - var whateverRemains = rawId.Substring(indexOfProviders + providersKey.Length); - var firstSlashIndex = whateverRemains.IndexOf('/'); - if (firstSlashIndex < 0) - return string.Empty; - return whateverRemains.Substring(firstSlashIndex + 1); - } - - /// - /// An extension method for supporting replacing one dictionary content with another one. - /// This is used to support resource tags. - /// - /// The destination dictionary in which the content will be replaced. - /// The source dictionary from which the content is copied from. - /// The destination dictionary that has been altered. - public static IDictionary ReplaceWith(this IDictionary dest, IDictionary src) - { - dest.Clear(); - foreach (var kv in src) - { - dest.Add(kv); - } - - return dest; - } - - public static async Task FirstOrDefaultAsync( - this AsyncPageable source, - Func predicate, - CancellationToken token = default) - where TSource : notnull - { - if (source == null) - throw new ArgumentNullException(nameof(source)); - if (predicate == null) - throw new ArgumentNullException(nameof(predicate)); - - token.ThrowIfCancellationRequested(); - - await foreach (var item in source.ConfigureAwait(false)) - { - token.ThrowIfCancellationRequested(); - - if (predicate(item)) - { - return item; - } - } - - return default; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/TaskExtensions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/TaskExtensions.cs deleted file mode 100644 index 9748653782..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/TaskExtensions.cs +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Threading; -using System.Threading.Tasks; - -namespace Azure.Core.Pipeline -{ - internal static class TaskExtensions - { - public static WithCancellationTaskAwaitable AwaitWithCancellation(this Task task, CancellationToken cancellationToken) - => new WithCancellationTaskAwaitable(task, cancellationToken); - - public static WithCancellationTaskAwaitable AwaitWithCancellation(this Task task, CancellationToken cancellationToken) - => new WithCancellationTaskAwaitable(task, cancellationToken); - - public static WithCancellationValueTaskAwaitable AwaitWithCancellation(this ValueTask task, CancellationToken cancellationToken) - => new WithCancellationValueTaskAwaitable(task, cancellationToken); - - public static T EnsureCompleted(this Task task) - { -#if DEBUG - VerifyTaskCompleted(task.IsCompleted); -#endif -#pragma warning disable AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead. - return task.GetAwaiter().GetResult(); -#pragma warning restore AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead. - } - - public static void EnsureCompleted(this Task task) - { -#if DEBUG - VerifyTaskCompleted(task.IsCompleted); -#endif -#pragma warning disable AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead. - task.GetAwaiter().GetResult(); -#pragma warning restore AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead. - } - - public static T EnsureCompleted(this ValueTask task) - { -#if DEBUG - VerifyTaskCompleted(task.IsCompleted); -#endif -#pragma warning disable AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead. - return task.GetAwaiter().GetResult(); -#pragma warning restore AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead. - } - - public static void EnsureCompleted(this ValueTask task) - { -#if DEBUG - VerifyTaskCompleted(task.IsCompleted); -#endif -#pragma warning disable AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead. - task.GetAwaiter().GetResult(); -#pragma warning restore AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead. - } - - public static Enumerable EnsureSyncEnumerable(this IAsyncEnumerable asyncEnumerable) => new Enumerable(asyncEnumerable); - - public static ConfiguredValueTaskAwaitable EnsureCompleted(this ConfiguredValueTaskAwaitable awaitable, bool async) - { - if (!async) - { -#if DEBUG - VerifyTaskCompleted(awaitable.GetAwaiter().IsCompleted); -#endif - } - return awaitable; - } - - public static ConfiguredValueTaskAwaitable EnsureCompleted(this ConfiguredValueTaskAwaitable awaitable, bool async) - { - if (!async) - { -#if DEBUG - VerifyTaskCompleted(awaitable.GetAwaiter().IsCompleted); -#endif - } - return awaitable; - } - - [Conditional("DEBUG")] - private static void VerifyTaskCompleted(bool isCompleted) - { - if (!isCompleted) - { - if (Debugger.IsAttached) - { - Debugger.Break(); - } - // Throw an InvalidOperationException instead of using - // Debug.Assert because that brings down nUnit immediately - throw new InvalidOperationException("Task is not completed"); - } - } - - /// - /// Both and are defined as public structs so that foreach can use duck typing - /// to call and avoid heap memory allocation. - /// Please don't delete this method and don't make these types private. - /// - /// - public readonly struct Enumerable : IEnumerable - { - private readonly IAsyncEnumerable _asyncEnumerable; - - public Enumerable(IAsyncEnumerable asyncEnumerable) => _asyncEnumerable = asyncEnumerable; - - public Enumerator GetEnumerator() => new Enumerator(_asyncEnumerable.GetAsyncEnumerator()); - - IEnumerator IEnumerable.GetEnumerator() => new Enumerator(_asyncEnumerable.GetAsyncEnumerator()); - - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - } - - public readonly struct Enumerator : IEnumerator - { - private readonly IAsyncEnumerator _asyncEnumerator; - - public Enumerator(IAsyncEnumerator asyncEnumerator) => _asyncEnumerator = asyncEnumerator; - -#pragma warning disable AZC0107 // Do not call public asynchronous method in synchronous scope. - public bool MoveNext() => _asyncEnumerator.MoveNextAsync().EnsureCompleted(); -#pragma warning restore AZC0107 // Do not call public asynchronous method in synchronous scope. - - public void Reset() => throw new NotSupportedException($"{GetType()} is a synchronous wrapper for {_asyncEnumerator.GetType()} async enumerator, which can't be reset, so IEnumerable.Reset() calls aren't supported."); - - public T Current => _asyncEnumerator.Current; - - object IEnumerator.Current => Current; - -#pragma warning disable AZC0107 // Do not call public asynchronous method in synchronous scope. - public void Dispose() => _asyncEnumerator.DisposeAsync().EnsureCompleted(); -#pragma warning restore AZC0107 // Do not call public asynchronous method in synchronous scope. - } - - public readonly struct WithCancellationTaskAwaitable - { - private readonly CancellationToken _cancellationToken; - private readonly ConfiguredTaskAwaitable _awaitable; - - public WithCancellationTaskAwaitable(Task task, CancellationToken cancellationToken) - { - _awaitable = task.ConfigureAwait(false); - _cancellationToken = cancellationToken; - } - - public WithCancellationTaskAwaiter GetAwaiter() => new WithCancellationTaskAwaiter(_awaitable.GetAwaiter(), _cancellationToken); - } - - public readonly struct WithCancellationTaskAwaitable - { - private readonly CancellationToken _cancellationToken; - private readonly ConfiguredTaskAwaitable _awaitable; - - public WithCancellationTaskAwaitable(Task task, CancellationToken cancellationToken) - { - _awaitable = task.ConfigureAwait(false); - _cancellationToken = cancellationToken; - } - - public WithCancellationTaskAwaiter GetAwaiter() => new WithCancellationTaskAwaiter(_awaitable.GetAwaiter(), _cancellationToken); - } - - public readonly struct WithCancellationValueTaskAwaitable - { - private readonly CancellationToken _cancellationToken; - private readonly ConfiguredValueTaskAwaitable _awaitable; - - public WithCancellationValueTaskAwaitable(ValueTask task, CancellationToken cancellationToken) - { - _awaitable = task.ConfigureAwait(false); - _cancellationToken = cancellationToken; - } - - public WithCancellationValueTaskAwaiter GetAwaiter() => new WithCancellationValueTaskAwaiter(_awaitable.GetAwaiter(), _cancellationToken); - } - - public readonly struct WithCancellationTaskAwaiter : ICriticalNotifyCompletion - { - private readonly CancellationToken _cancellationToken; - private readonly ConfiguredTaskAwaitable.ConfiguredTaskAwaiter _taskAwaiter; - - public WithCancellationTaskAwaiter(ConfiguredTaskAwaitable.ConfiguredTaskAwaiter awaiter, CancellationToken cancellationToken) - { - _taskAwaiter = awaiter; - _cancellationToken = cancellationToken; - } - - public bool IsCompleted => _taskAwaiter.IsCompleted || _cancellationToken.IsCancellationRequested; - - public void OnCompleted(Action continuation) => _taskAwaiter.OnCompleted(WrapContinuation(continuation)); - - public void UnsafeOnCompleted(Action continuation) => _taskAwaiter.UnsafeOnCompleted(WrapContinuation(continuation)); - - public void GetResult() - { - Debug.Assert(IsCompleted); - if (!_taskAwaiter.IsCompleted) - { - _cancellationToken.ThrowIfCancellationRequested(); - } - _taskAwaiter.GetResult(); - } - - private Action WrapContinuation(in Action originalContinuation) - => _cancellationToken.CanBeCanceled - ? new WithCancellationContinuationWrapper(originalContinuation, _cancellationToken).Continuation - : originalContinuation; - } - - public readonly struct WithCancellationTaskAwaiter : ICriticalNotifyCompletion - { - private readonly CancellationToken _cancellationToken; - private readonly ConfiguredTaskAwaitable.ConfiguredTaskAwaiter _taskAwaiter; - - public WithCancellationTaskAwaiter(ConfiguredTaskAwaitable.ConfiguredTaskAwaiter awaiter, CancellationToken cancellationToken) - { - _taskAwaiter = awaiter; - _cancellationToken = cancellationToken; - } - - public bool IsCompleted => _taskAwaiter.IsCompleted || _cancellationToken.IsCancellationRequested; - - public void OnCompleted(Action continuation) => _taskAwaiter.OnCompleted(WrapContinuation(continuation)); - - public void UnsafeOnCompleted(Action continuation) => _taskAwaiter.UnsafeOnCompleted(WrapContinuation(continuation)); - - public T GetResult() - { - Debug.Assert(IsCompleted); - if (!_taskAwaiter.IsCompleted) - { - _cancellationToken.ThrowIfCancellationRequested(); - } - return _taskAwaiter.GetResult(); - } - - private Action WrapContinuation(in Action originalContinuation) - => _cancellationToken.CanBeCanceled - ? new WithCancellationContinuationWrapper(originalContinuation, _cancellationToken).Continuation - : originalContinuation; - } - - public readonly struct WithCancellationValueTaskAwaiter : ICriticalNotifyCompletion - { - private readonly CancellationToken _cancellationToken; - private readonly ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter _taskAwaiter; - - public WithCancellationValueTaskAwaiter(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter, CancellationToken cancellationToken) - { - _taskAwaiter = awaiter; - _cancellationToken = cancellationToken; - } - - public bool IsCompleted => _taskAwaiter.IsCompleted || _cancellationToken.IsCancellationRequested; - - public void OnCompleted(Action continuation) => _taskAwaiter.OnCompleted(WrapContinuation(continuation)); - - public void UnsafeOnCompleted(Action continuation) => _taskAwaiter.UnsafeOnCompleted(WrapContinuation(continuation)); - - public T GetResult() - { - Debug.Assert(IsCompleted); - if (!_taskAwaiter.IsCompleted) - { - _cancellationToken.ThrowIfCancellationRequested(); - } - return _taskAwaiter.GetResult(); - } - - private Action WrapContinuation(in Action originalContinuation) - => _cancellationToken.CanBeCanceled - ? new WithCancellationContinuationWrapper(originalContinuation, _cancellationToken).Continuation - : originalContinuation; - } - - private class WithCancellationContinuationWrapper - { - private Action _originalContinuation; - private readonly CancellationTokenRegistration _registration; - - public WithCancellationContinuationWrapper(Action originalContinuation, CancellationToken cancellationToken) - { - Action continuation = ContinuationImplementation; - _originalContinuation = originalContinuation; - _registration = cancellationToken.Register(continuation); - Continuation = continuation; - } - - public Action Continuation { get; } - - private void ContinuationImplementation() - { - Action originalContinuation = Interlocked.Exchange(ref _originalContinuation, null); - if (originalContinuation != null) - { - _registration.Dispose(); - originalContinuation(); - } - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/TypeFormatters.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/TypeFormatters.cs deleted file mode 100644 index 6bb51d611c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/TypeFormatters.cs +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Xml; - -namespace Azure.Core -{ - internal class TypeFormatters - { - private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; - public static string DefaultNumberFormat { get; } = "G"; - - public static string ToString(bool value) => value ? "true" : "false"; - - public static string ToString(DateTime value, string format) => value.Kind switch - { - DateTimeKind.Utc => ToString((DateTimeOffset)value, format), - _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Azure SDK requires it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") - }; - - public static string ToString(DateTimeOffset value, string format) => format switch - { - "D" => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), - "U" => value.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), - "O" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), - "o" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), - "R" => value.ToString("r", CultureInfo.InvariantCulture), - _ => value.ToString(format, CultureInfo.InvariantCulture) - }; - - public static string ToString(TimeSpan value, string format) => format switch - { - "P" => XmlConvert.ToString(value), - _ => value.ToString(format, CultureInfo.InvariantCulture) - }; - - public static string ToString(byte[] value, string format) => format switch - { - "U" => ToBase64UrlString(value), - "D" => Convert.ToBase64String(value), - _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) - }; - - public static string ToBase64UrlString(byte[] value) - { - var numWholeOrPartialInputBlocks = checked(value.Length + 2) / 3; - var size = checked(numWholeOrPartialInputBlocks * 4); - var output = new char[size]; - - var numBase64Chars = Convert.ToBase64CharArray(value, 0, value.Length, output, 0); - - // Fix up '+' -> '-' and '/' -> '_'. Drop padding characters. - int i = 0; - for (; i < numBase64Chars; i++) - { - var ch = output[i]; - if (ch == '+') - { - output[i] = '-'; - } - else if (ch == '/') - { - output[i] = '_'; - } - else if (ch == '=') - { - // We've reached a padding character; truncate the remainder. - break; - } - } - - return new string(output, 0, i); - } - - public static byte[] FromBase64UrlString(string value) - { - var paddingCharsToAdd = GetNumBase64PaddingCharsToAddForDecode(value.Length); - - var output = new char[value.Length + paddingCharsToAdd]; - - int i; - for (i = 0; i < value.Length; i++) - { - var ch = value[i]; - if (ch == '-') - { - output[i] = '+'; - } - else if (ch == '_') - { - output[i] = '/'; - } - else - { - output[i] = ch; - } - } - - for (; i < output.Length; i++) - { - output[i] = '='; - } - - return Convert.FromBase64CharArray(output, 0, output.Length); - } - - private static int GetNumBase64PaddingCharsToAddForDecode(int inputLength) - { - switch (inputLength % 4) - { - case 0: - return 0; - case 2: - return 2; - case 3: - return 1; - default: - throw new InvalidOperationException("Malformed input"); - } - } - - public static DateTimeOffset ParseDateTimeOffset(string value, string format) - { - return format switch - { - "U" => DateTimeOffset.FromUnixTimeSeconds(long.Parse(value, CultureInfo.InvariantCulture)), - _ => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) - }; - } - - public static TimeSpan ParseTimeSpan(string value, string format) => format switch - { - "P" => XmlConvert.ToTimeSpan(value), - _ => TimeSpan.ParseExact(value, format, CultureInfo.InvariantCulture) - }; - - public static string ConvertToString(object? value, string? format = null) - => value switch - { - null => "null", - string s => s, - bool b => ToString(b), - int or float or double or long or decimal => ((IFormattable)value).ToString(DefaultNumberFormat, CultureInfo.InvariantCulture), - byte[] b when format != null => ToString(b, format), - IEnumerable s => string.Join(",", s), - DateTimeOffset dateTime when format != null => ToString(dateTime, format), - TimeSpan timeSpan when format != null => ToString(timeSpan, format), - TimeSpan timeSpan => XmlConvert.ToString(timeSpan), - Guid guid => guid.ToString(), - BinaryData binaryData => TypeFormatters.ConvertToString(binaryData.ToArray(), format), - _ => value.ToString()! - }; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/TypeReferenceTypeAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/TypeReferenceTypeAttribute.cs deleted file mode 100644 index dce5c4f331..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/TypeReferenceTypeAttribute.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -namespace Azure.Core -{ - /// - /// An attribute class indicating to Autorest a reference type which can replace a type in target SDKs. - /// - [AttributeUsage(AttributeTargets.Class)] - internal class TypeReferenceTypeAttribute : Attribute - { - /// - /// Constructs a new instance of . - /// - public TypeReferenceTypeAttribute() - : this(false, Array.Empty()) - { - } - - /// - /// Constructs a new instance of . - /// - /// Whether to allow replacement to occur when the type to be replaced - /// contains extra properties as compared to the reference type attributed with that it will - /// be replaced with. Defaults to false. - /// An array of internal properties to include for the reference type when evaluating whether type - /// replacement should occur. When evaluating a type for replacement with a reference type, all internal properties are considered on the - /// type to be replaced. Thus this parameter can be used to specify internal properties to allow replacement to occur on a type with internal - /// properties. - public TypeReferenceTypeAttribute(bool ignoreExtraProperties, string[] internalPropertiesToInclude) - { - IgnoreExtraProperties = ignoreExtraProperties; - InternalPropertiesToInclude = internalPropertiesToInclude; - } - - public bool IgnoreExtraProperties { get; } - public string[] InternalPropertiesToInclude { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/VoidValue.cs b/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/VoidValue.cs deleted file mode 100644 index cb52e0eafb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/Shared/VoidValue.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Text.Json; - -namespace Azure.Core -{ - internal readonly struct VoidValue { } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/autorest.md b/tests/dotnet-upgrade/dotnet-aot-compat/after/autorest.md deleted file mode 100644 index 3735f0952b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/autorest.md +++ /dev/null @@ -1,839 +0,0 @@ -# Generated code configuration - -Run `dotnet build /t:GenerateCode` to generate code. - -```yaml -azure-arm: true -arm-core: true -clear-output-folder: true -skip-csproj: true -model-namespace: false -public-clients: false -head-as-boolean: false -modelerfour: - lenient-model-deduplication: true -use-model-reader-writer: true -deserialize-null-collection-as-null-value: true -enable-bicep-serialization: true - -#mgmt-debug: -# show-serialized-names: true - -batch: - - tag: package-common-type - - tag: package-resources - - tag: package-management -``` - -### Tag: package-common-type - -These settings apply only when `--tag=package-common-type` is specified on the command line. - -``` yaml $(tag) == 'package-common-type' -output-folder: $(this-folder)/Common/Generated -sample-gen: - output-folder: $(this-folder)/../samples/Generated - clear-output-folder: true -namespace: Azure.ResourceManager -input-file: - - https://github.com/Azure/azure-rest-api-specs/blob/78eac0bd58633028293cb1ec1709baa200bed9e2/specification/common-types/resource-management/v3/types.json - - https://github.com/Azure/azure-rest-api-specs/blob/78eac0bd58633028293cb1ec1709baa200bed9e2/specification/common-types/resource-management/v4/managedidentity.json - -format-by-name-rules: - 'tenantId': 'uuid' - 'etag': 'etag' - 'location': 'azure-location' - '*Uri': 'Uri' - '*Uris': 'Uri' - -acronym-mapping: - CPU: Cpu - CPUs: Cpus - Os: OS - Ip: IP - Ips: IPs - ID: Id - IDs: Ids - VM: Vm - VMs: Vms - Vmos: VmOS - VMScaleSet: VmScaleSet - DNS: Dns - VPN: Vpn - NAT: Nat - WAN: Wan - Ipv4: IPv4 - Ipv6: IPv6 - Ipsec: IPsec - SSO: Sso - URI: Uri - -directive: - - from: types.json - where: $.definitions.Resource - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-ms-client-name"] = "ResourceData"; - $["x-accessibility"] = "public"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; - - from: types.json - where: $.definitions.TrackedResource - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-ms-client-name"] = "TrackedResourceData"; - $["x-accessibility"] = "public"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; - - from: types.json - where: $.definitions.Plan - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-accessibility"] = "public"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; - - from: types.json - where: $.definitions.Sku - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-accessibility"] = "public"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; - - from: types.json - where: $.definitions.systemData - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-accessibility"] = "public"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; -# Workaround for the issue that SystemData lost readonly attribute: https://github.com/Azure/autorest/issues/4269 - - from: types.json - where: $.definitions.systemData.properties.* - transform: > - $["readOnly"] = true; - - from: types.json - where: $.definitions.encryptionProperties - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-accessibility"] = "public"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; - - from: types.json - where: $.definitions.KeyVaultProperties - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-accessibility"] = "public"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; - - from: types.json - where: $.definitions.*.properties[?(@.enum)] - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-accessibility"] = "public"; - - from: types.json - where: $.definitions.OperationStatusResult - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; - - from: types.json - where: $.definitions.OperationStatusResult.properties.* - transform: > - $["readOnly"] = true; - - from: managedidentity.json - where: $.definitions.SystemAssignedServiceIdentity - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-accessibility"] = "public"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; - $.properties.type["x-ms-client-name"] = "SystemAssignedServiceIdentityType"; - - from: managedidentity.json - where: $.definitions.UserAssignedIdentity - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-accessibility"] = "public"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; -``` - -### Tag: package-resources - -These settings apply only when `--tag=package-resources` is specified on the command line. - -``` yaml $(tag) == 'package-resources' -output-folder: $(this-folder)/Resources/Generated -sample-gen: - output-folder: $(this-folder)/../samples/Generated - clear-output-folder: false -namespace: Azure.ResourceManager.Resources -title: ResourceManagementClient -input-file: - - https://github.com/Azure/azure-rest-api-specs/blob/817861452040bf29d14b57ac7418560e4680e06e/specification/resources/resource-manager/Microsoft.Authorization/stable/2022-06-01/policyAssignments.json - - https://github.com/Azure/azure-rest-api-specs/blob/90a65cb3135d42438a381eb8bb5461a2b99b199f/specification/resources/resource-manager/Microsoft.Authorization/stable/2021-06-01/policyDefinitions.json - - https://github.com/Azure/azure-rest-api-specs/blob/90a65cb3135d42438a381eb8bb5461a2b99b199f/specification/resources/resource-manager/Microsoft.Authorization/stable/2021-06-01/policySetDefinitions.json - - https://github.com/Azure/azure-rest-api-specs/blob/78eac0bd58633028293cb1ec1709baa200bed9e2/specification/resources/resource-manager/Microsoft.Authorization/stable/2020-09-01/dataPolicyManifests.json - - https://github.com/Azure/azure-rest-api-specs/blob/78eac0bd58633028293cb1ec1709baa200bed9e2/specification/resources/resource-manager/Microsoft.Authorization/stable/2020-05-01/locks.json - - https://github.com/Azure/azure-rest-api-specs/blob/90a65cb3135d42438a381eb8bb5461a2b99b199f/specification/resources/resource-manager/Microsoft.Resources/stable/2022-09-01/resources.json - - https://github.com/Azure/azure-rest-api-specs/blob/78eac0bd58633028293cb1ec1709baa200bed9e2/specification/resources/resource-manager/Microsoft.Resources/stable/2022-12-01/subscriptions.json - - https://github.com/Azure/azure-rest-api-specs/blob/78eac0bd58633028293cb1ec1709baa200bed9e2/specification/resources/resource-manager/Microsoft.Features/stable/2021-07-01/features.json - -list-exception: - - /{resourceId} - -request-path-to-resource-data: - # subscription does not have name and type - /subscriptions/{subscriptionId}: Subscription - # tenant does not have name and type - /: Tenant - # provider does not have name and type - /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}: ResourceProvider - -request-path-is-non-resource: - - /subscriptions/{subscriptionId}/locations - -request-path-to-parent: - /subscriptions: /subscriptions/{subscriptionId} - /tenants: / - /subscriptions/{subscriptionId}/locations: /subscriptions/{subscriptionId} - /subscriptions/{subscriptionId}/providers: /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}: /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - -request-path-to-resource-type: - /subscriptions/{subscriptionId}/locations: Microsoft.Resources/locations - /tenants: Microsoft.Resources/tenants - /: Microsoft.Resources/tenants - /subscriptions: Microsoft.Resources/subscriptions - /subscriptions/{subscriptionId}/resourcegroups: Microsoft.Resources/resourceGroups - /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}: Microsoft.Resources/features - /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}: Microsoft.Resources/providers - /providers: Microsoft.Resources/providers - -request-path-to-scope-resource-types: - /{scope}/providers/Microsoft.Authorization/locks/{lockName}: - - subscriptions - - resourceGroups - - "*" -operation-positions: - CheckResourceName: collection - -operation-groups-to-omit: - - Deployments - - DeploymentOperations - - AuthorizationOperations - -override-operation-name: - Tags_List: GetAllPredefinedTags - Tags_DeleteValue: DeletePredefinedTagValue - Tags_CreateOrUpdateValue: CreateOrUpdatePredefinedTagValue - Tags_CreateOrUpdate: CreateOrUpdatePredefinedTag - Tags_Delete: DeletePredefinedTag - Providers_ListAtTenantScope: GetTenantResourceProviders - Providers_GetAtTenantScope: GetTenantResourceProvider - Resources_List: GetGenericResources - Resources_ListByResourceGroup: GetGenericResources - Resources_MoveResources: MoveResources - Resources_ValidateMoveResources: ValidateMoveResources - -no-property-type-replacement: ResourceProviderData;ResourceProvider - -operations-to-skip-lro-api-version-override: -- Tags_CreateOrUpdateAtScope -- Tags_UpdateAtScope -- Tags_DeleteAtScope - -generate-arm-resource-extensions: -- /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} -- /{scope}/providers/Microsoft.Authorization/locks/{lockName} - -format-by-name-rules: - 'tenantId': 'uuid' - 'etag': 'etag' - 'location': 'azure-location' - '*Uri': 'Uri' - '*Uris': 'Uri' - -keep-plural-enums: - - ResourceTypeAliasPathAttributes - -acronym-mapping: - CPU: Cpu - CPUs: Cpus - Os: OS - Ip: IP - Ips: IPs - ID: Id - IDs: Ids - VM: Vm - VMs: Vms - Vmos: VmOS - VMScaleSet: VmScaleSet - DNS: Dns - VPN: Vpn - NAT: Nat - WAN: Wan - Ipv4: IPv4 - Ipv6: IPv6 - Ipsec: IPsec - SSO: Sso - URI: Uri - -rename-mapping: - PolicyAssignment.identity: ManagedIdentity - Override: PolicyOverride - OverrideKind: PolicyOverrideKind - Selector: ResourceSelectorExpression - SelectorKind: ResourceSelectorKind - Location: LocationExpanded - ResourcesMoveContent.targetResourceGroup: targetResourceGroupId|arm-id - LocationMetadata.pairedRegion: PairedRegions - CheckResourceNameResult: ResourceNameValidationResult - CheckResourceNameResult.type: ResourceType|resource-type - ResourceName: ResourceNameValidationContent - ResourceName.type: ResourceType|resource-type - ResourceNameStatus: ResourceNameValidationStatus - Resource: ResourceData - TrackedResource: TrackedResourceData - -directive: - # These methods can be replaced by using other methods in the same operation group, remove for Preview. - - remove-operation: PolicyAssignments_UpdateById - - remove-operation: PolicyAssignments_DeleteById - - remove-operation: PolicyAssignments_CreateById - - remove-operation: PolicyAssignments_GetById - - remove-operation: ManagementLocks_CreateOrUpdateAtResourceGroupLevel - - remove-operation: ManagementLocks_CreateOrUpdateAtResourceLevel - - remove-operation: ManagementLocks_CreateOrUpdateAtSubscriptionLevel - - remove-operation: ManagementLocks_DeleteAtResourceGroupLevel - - remove-operation: ManagementLocks_DeleteAtResourceLevel - - remove-operation: ManagementLocks_DeleteAtSubscriptionLevel - - remove-operation: ManagementLocks_GetAtResourceGroupLevel - - remove-operation: ManagementLocks_GetAtResourceLevel - - remove-operation: ManagementLocks_GetAtSubscriptionLevel - - remove-operation: ManagementLocks_ListAtResourceGroupLevel - - remove-operation: ManagementLocks_ListAtResourceLevel - - remove-operation: ManagementLocks_ListAtSubscriptionLevel - # These methods was not in the previous manual code, remove them for the first generation and can add them back later. - - remove-operation: ResourceGroups_CheckExistence - - remove-operation: Resources_CheckExistenceById - - remove-operation: Resources_CheckExistence - - remove-operation: Resources_CreateOrUpdate - - remove-operation: Resources_Update - - remove-operation: Resources_Get - - remove-operation: Resources_Delete - - remove-operation: Providers_RegisterAtManagementGroupScope - - remove-operation: Subscriptions_CheckZonePeers - - remove-operation: AuthorizationOperations_List - # Deduplicate - - from: subscriptions.json - where: '$.paths["/providers/Microsoft.Resources/operations"].get' - transform: > - $["operationId"] = "Operations_ListSubscriptionOperations"; - reason: Rename duplicate operation Id. - - from: resources.json - where: '$.paths["/providers/Microsoft.Resources/operations"].get' - transform: > - $["operationId"] = "Operations_ListResourcesOperations"; - reason: Rename duplicate operation Id. - - from: features.json - where: '$.paths["/providers/Microsoft.Features/operations"].get' - transform: > - $["operationId"] = "Operations_ListFeaturesOperations"; - reason: Add operation group so that we can omit related models by the operation group. - - from: links.json - where: $.definitions - transform: > - $["OperationListResult"]["x-ms-client-name"] = "ResourceLinkOperationListResult"; - $["Operation"]["x-ms-client-name"] = "ResourceLinksOperation"; - - from: subscriptions.json - where: $.definitions - transform: > - $["OperationListResult"] = undefined; - $["Operation"] = undefined; - - from: features.json - where: $.definitions - transform: > - $["OperationListResult"]["x-ms-client-name"] = "FeatureOperationListResult"; - $["Operation"]["x-ms-client-name"] = "FeatureOperation"; - $["Operation"]["properties"]["displayOfFeature"] = $["Operation"]["properties"]["display"]; - $["Operation"]["properties"]["display"] = undefined; - - from: features.json - where: $.definitions.ErrorResponse - transform: > - $["x-ms-client-name"] = "FeatureErrorResponse"; - # remove the systemData property because we already included this property in its base class and the type replacement somehow does not work in resourcemanager - - from: policyAssignments.json - where: $.definitions.PolicyAssignment.properties.systemData - transform: return undefined; - - from: policyDefinitions.json - where: $.definitions.PolicyDefinition.properties.systemData - transform: return undefined; - - from: policySetDefinitions.json - where: $.definitions.PolicySetDefinition.properties.systemData - transform: return undefined; - - from: resources.json - where: $.definitions.ExtendedLocation - transform: > - $["x-namespace"] = "Azure.ResourceManager.Resources.Models"; - - - rename-model: - from: Provider - to: ResourceProvider - - rename-model: - from: ProviderListResult - to: ResourceProviderListResult - - rename-model: - from: TenantIdDescription - to: Tenant - - rename-model: - from: Tags - to: Tag - - rename-model: - from: TagsResource - to: TagResource - - rename-model: - from: TagsPatchResource - to: TagPatchResource - - rename-model: - from: TagCount - to: PredefinedTagCount - - rename-model: - from: TagValue - to: PredefinedTagValue - - rename-model: - from: TagDetails - to: PredefinedTag - - rename-model: - from: TagsListResult - to: PredefinedTagsListResult - - rename-model: - from: FeatureResult - to: Feature - - rename-model: - from: Resource - to: TrackedResourceExtendedData - - rename-model: - from: ResourcesMoveInfo - to: ResourcesMoveContent - - from: resources.json - where: $.definitions.Provider - transform: - $["x-ms-client-name"] = "ResourceProvider"; - - from: resources.json - where: $.definitions.Alias - transform: - $["x-ms-client-name"] = "ResourceTypeAlias"; - - from: resources.json - where: $.definitions.AliasPath - transform: - $["x-ms-client-name"] = "ResourceTypeAliasPath"; - - from: resources.json - where: $.definitions.AliasPathMetadata.properties.attributes["x-ms-enum"] - transform: - $["name"] = "ResourceTypeAliasPathAttributes"; - - from: resources.json - where: $.definitions.AliasPathMetadata - transform: - $["x-ms-client-name"] = "ResourceTypeAliasPathMetadata"; - - from: resources.json - where: $.definitions.AliasPathMetadata.properties.type["x-ms-enum"] - transform: - $["name"] = "ResourceTypeAliasPathTokenType"; - - from: resources.json - where: $.definitions.AliasPattern - transform: - $["x-ms-client-name"] = "ResourceTypeAliasPattern"; - - from: resources.json - where: $.definitions.AliasPattern.properties.type["x-ms-enum"] - transform: - $["name"] = "ResourceTypeAliasPatternType"; - - from: resources.json - where: $.definitions.Alias.properties.type["x-ms-enum"] - transform: - $["name"] = "ResourceTypeAliasType"; - - from: policyDefinitions.json - where: $.definitions.ParameterDefinitionsValue - transform: - $["x-ms-client-name"] = "ArmPolicyParameter"; - - from: policyDefinitions.json - where: $.definitions.ParameterDefinitionsValue.properties.type["x-ms-enum"] - transform: - $["name"] = "ArmPolicyParameterType"; - - from: policyAssignments.json - where: $.definitions.ParameterValuesValue - transform: - $["x-ms-client-name"] = "ArmPolicyParameterValue"; - - remove-model: DeploymentExtendedFilter - - remove-model: ResourceProviderOperationDisplayProperties - - from: subscriptions.json - where: $.paths - transform: > - $["/"] = { - "get": { - "tags": [ - "Tenants" - ], - "operationId": "Tenants_Get", - "description": "Gets details about the default tenant.", - "parameters": [ - { - "$ref": "../../../../../common-types/resource-management/v5/types.json#/parameters/ApiVersionParameter" - } - ], - "responses": { - "200": { - "description": "OK - Returns information about the tenant.", - "schema": { - "$ref": "#/definitions/Tenant" - } - }, - "default": { - "description": "Error response describing why the operation failed.", - "schema": { - "$ref": "#/definitions/CloudError" - } - } - } - } - } - reason: add a fake tenant get operation so that we can generate a tenant where all the Get[TenantResources] operations can be autogen in it. The get operation will be removed with codegen suppress attributes. - - - from: resources.json - where: $.definitions - transform: > - $["TenantResourceProvider"] = { - "properties": { - "namespace": { - "type": "string", - "description": "The namespace of the resource provider." - }, - "resourceTypes": { - "readOnly": true, - "type": "array", - "items": { - "$ref": "#/definitions/ProviderResourceType" - }, - "description": "The collection of provider resource types." - } - }, - "description": "Resource provider information." - } - reason: This is the real response for a tenant provider. - - from: resources.json - where: $.definitions - transform: > - $["TenantResourceProviderListResult"] = { - "properties": { - "value": { - "type": "array", - "items": { - "$ref": "#/definitions/TenantResourceProvider" - }, - "description": "An array of resource providers." - }, - "nextLink": { - "readOnly": true, - "type": "string", - "description": "The URL to use for getting the next set of results." - } - }, - "description": "List of resource providers." - } - - from: resources.json - where: $.definitions.TenantResourceProviderListResult.properties.value.items["$ref"] - transform: return "#/definitions/TenantResourceProvider" - - from: resources.json - where: $.paths["/providers"].get.responses["200"].schema["$ref"] - transform: return "#/definitions/TenantResourceProviderListResult" - - from: resources.json - where: $.paths["/providers/{resourceProviderNamespace}"].get.responses["200"].schema["$ref"] - transform: return "#/definitions/TenantResourceProvider" - - - from: resources.json - where: $.definitions.Identity.properties.type["x-ms-enum"] - transform: > - $["name"] = "GenericResourceIdentityType"; - $["modelAsString"] = true; - - from: resources.json - where: $.definitions.Identity - transform: > - $["required"] = ["type"] - - from: resources.json - where: $.definitions.Identity - transform: > - $["x-ms-client-name"] = "GenericResourceIdentity"; - - from: policyAssignments.json - where: $.definitions.Identity.properties.type["x-ms-enum"] - transform: $["name"] = "PolicyAssignmentIdentityType" - - from: policyAssignments.json - where: $.definitions.Identity - transform: > - $["x-ms-client-name"] = "PolicyAssignmentIdentity"; - - from: locks.json - where: $.paths..parameters[?(@.name === "scope")] - transform: > - $["x-ms-skip-url-encoding"] = true - # Rename GenericResourceExpanded to GenericResource and use it as the schema for both single resource operation and collection operation. - - from: resources.json - where: $.definitions.ResourceListResult.properties.value.items["$ref"] - transform: > - $ = "#/definitions/GenericResource" - - from: resources.json - where: $.definitions - transform: > - $.GenericResource.properties["createdTime"] = $.GenericResourceExpanded.properties["createdTime"]; - $.GenericResource.properties["changedTime"] = $.GenericResourceExpanded.properties["changedTime"]; - $.GenericResource.properties["provisioningState"] = $.GenericResourceExpanded.properties["provisioningState"]; - delete $.GenericResourceExpanded; - - from: locks.json - where: $.definitions.ManagementLockObject - transform: $["x-ms-client-name"] = "ManagementLock" - - from: links.json - where: $.definitions.ResourceLink.properties.type - transform: > - $["x-ms-client-name"] = "ResourceType"; - $["type"] = "string"; - - from: dataPolicyManifests.json - where: $.definitions.DataEffect - transform: > - $["x-ms-client-name"] = "DataPolicyManifestEffect"; - - from: locks.json - where: $.definitions.ManagementLockProperties.properties.level["x-ms-enum"] - transform: > - $["name"] = "ManagementLockLevel" - - from: subscriptions.json - where: $.definitions.Subscription.properties.tenantId - transform: > - $['format'] = "uuid" - - from: subscriptions.json - where: $.definitions.Tenant.properties.tenantId - transform: > - $['format'] = "uuid" - - from: subscriptions.json - where: $.definitions.ManagedByTenant.properties.tenantId - transform: > - $['format'] = "uuid" - - from: resources.json - where: $.definitions.ResourcesMoveInfo.properties.resources.items - transform: > - $["x-ms-format"] = "arm-id" - - from: resources.json - where: $.definitions.RoleDefinition - transform: > - $["x-ms-client-name"] = "AzureRoleDefinition"; - - from: resources.json - where: $.definitions.TagPatchResource.properties.operation["x-ms-enum"] - transform: > - $["name"] = "TagPatchMode" - - from: resources.json - where: $.definitions.TagPatchResource.properties.operation - transform: > - $["x-ms-client-name"] = "PatchMode" - - from: dataPolicyManifests.json - where: $.definitions.DataManifestResourceFunctionsDefinition.properties.custom - transform: > - $["x-ms-client-name"] = "CustomDefinitions" - - from: policyAssignments.json - where: $.definitions.PolicyAssignmentProperties.properties.notScopes - transform: > - $["x-ms-client-name"] = "ExcludedScopes" - - from: resources.json - where: $.definitions.ExportTemplateRequest - transform: > - $["x-ms-client-name"] = "ExportTemplate" - - from: dataPolicyManifests.json - where: $.definitions.DataManifestCustomResourceFunctionDefinition.properties.fullyQualifiedResourceType - transform: > - $["x-ms-format"] = "resource-type" - - from: resources.json - where: $.definitions.Permission.properties.actions - transform: > - $["x-ms-client-name"] = "AllowedActions" - - from: resources.json - where: $.definitions.Permission.properties.notActions - transform: > - $["x-ms-client-name"] = "DeniedActions" - - from: resources.json - where: $.definitions.Permission.properties.dataActions - transform: > - $["x-ms-client-name"] = "AllowedDataActions" - - from: resources.json - where: $.definitions.Permission.properties.notDataActions - transform: > - $["x-ms-client-name"] = "DeniedDataActions" - - from: policyAssignments.json - where: $.definitions.PolicyAssignment.properties.location - transform: > - $["x-ms-format"] = "azure-location" - - from: resources.json - where: $.definitions.ProviderExtendedLocation.properties.location - transform: > - $["x-ms-format"] = "azure-location" -``` - -### Tag: package-management - -These settings apply only when `--tag=package-management` is specified on the command line. - -``` yaml $(tag) == 'package-management' -output-folder: $(this-folder)/ManagementGroup/Generated -sample-gen: - output-folder: $(this-folder)/../samples/Generated - clear-output-folder: false -namespace: Azure.ResourceManager.ManagementGroups -title: ManagementClient -input-file: - - https://github.com/Azure/azure-rest-api-specs/blob/90a65cb3135d42438a381eb8bb5461a2b99b199f/specification/managementgroups/resource-manager/Microsoft.Management/stable/2021-04-01/management.json -request-path-to-parent: - /providers/Microsoft.Management/checkNameAvailability: /providers/Microsoft.Management/managementGroups/{groupId} - /providers/Microsoft.Management/getEntities: /providers/Microsoft.Management/managementGroups/{groupId} -operation-positions: - ManagementGroups_CheckNameAvailability: collection - Entities_List: collection -operation-groups-to-omit: - - HierarchySettings - - TenantBackfill -no-property-type-replacement: DescendantParentGroupInfo - -format-by-name-rules: - 'tenantId': 'uuid' - 'etag': 'etag' - 'location': 'azure-location' - '*Uri': 'Uri' - '*Uris': 'Uri' - -rename-mapping: - EntityInfo: EntityData - Permissions: EntityPermission - Permissions.noaccess: NoAccess - SearchOptions: EntitySearchOption - SubscriptionUnderManagementGroup: ManagementGroupSubscription - -override-operation-name: - ManagementGroupSubscriptions_GetSubscription: GetManagementGroupSubscription - -acronym-mapping: - CPU: Cpu - CPUs: Cpus - Os: OS - Ip: IP - Ips: IPs - ID: Id - IDs: Ids - VM: Vm - VMs: Vms - Vmos: VmOS - VMScaleSet: VmScaleSet - DNS: Dns - VPN: Vpn - NAT: Nat - WAN: Wan - Ipv4: IPv4 - Ipv6: IPv6 - Ipsec: IPsec - SSO: Sso - URI: Uri -directive: - - rename-model: - from: CreateManagementGroupChildInfo - to: ManagementGroupChildOptions - - rename-model: - from: CreateParentGroupInfo - to: ManagementGroupParentCreateOptions - - rename-operation: - from: CheckNameAvailability - to: ManagementGroups_CheckNameAvailability - - rename-operation: - from: StartTenantBackfill - to: TenantBackfill_Start - - rename-operation: - from: TenantBackfillStatus - to: TenantBackfill_Status - - from: management.json - where: $.parameters.SkipTokenParameter - transform: > - $['x-ms-client-name'] = 'SkipToken' - - from: management.json - where: $.parameters.ExpandParameter - transform: > - $['x-ms-enum'] = { - name: "ManagementGroupExpandType", - modelAsString: true - } - - from: management.json - where: $.definitions.ManagementGroupListResult.properties.value.items - transform: > - $['$ref'] = "#/definitions/ManagementGroup" - - from: management.json - where: $.definitions.ManagementGroupInfo - transform: 'return undefined' - - remove-model: OperationResults - - from: management.json - where: $.definitions.CheckNameAvailabilityResult.properties.reason - transform: > - $['x-ms-enum'] = { - name: "ManagementGroupNameUnavailableReason" - } - - from: management.json - where: $.definitions.ManagementGroupChildType - transform: > - $['x-ms-enum'].modelAsString = true - - from: management.json - where: $.definitions.CheckNameAvailabilityResult - transform: > - $['x-ms-client-name'] = "ManagementGroupNameAvailabilityResult" - - from: management.json - where: $.parameters.SearchParameter - transform: > - $['x-ms-enum'] = { - name: "SearchOptions", - modelAsString: true - } - reason: omit operation group does not clean this enum parameter, rename it and then suppress with codegen attribute. - - from: management.json - where: $.parameters.EntityViewParameter - transform: > - $['x-ms-enum'] = { - name: "EntityViewOptions", - modelAsString: true - } - reason: omit operation group does not clean this enum parameter, rename it and then suppress with codegen attribute. - - remove-model: EntityHierarchyItem - - remove-model: EntityHierarchyItemProperties - - from: management.json - where: $.definitions.CreateManagementGroupProperties.properties.tenantId - transform: > - $['format'] = "uuid" - - from: management.json - where: $.definitions.DescendantInfo - transform: > - $['x-ms-client-name'] = "DescendantData" - - from: management.json - where: $.definitions.DescendantParentGroupInfo.properties.id - transform: > - $["x-ms-format"] = "arm-id" - - from: management.json - where: $.definitions.ManagementGroupDetails.properties.managementGroupAncestorsChain - transform: > - $["x-ms-client-name"] = "managementGroupAncestorChain" - - from: management.json - where: $.definitions.ManagementGroupDetails - transform: > - $["x-ms-client-name"] = "ManagementGroupInfo" - - from: management.json - where: $.definitions.ParentGroupInfo - transform: > - $["x-ms-client-name"] = "ParentManagementGroupInfo" - - from: management.json - where: $.definitions.ManagementGroupProperties.properties.tenantId - transform: > - $['format'] = "uuid" - - from: management.json - where: $.definitions - transform: > - $.CreateManagementGroupRequest.properties.type['x-ms-format'] = 'resource-type'; - $.CheckNameAvailabilityRequest["x-ms-client-name"] = "ManagementGroupNameAvailabilityContent"; - $.CheckNameAvailabilityRequest.properties.type['x-ms-client-name'] = "ResourceType"; - $.CheckNameAvailabilityRequest.properties.type['x-ms-constant'] = true; - $.CheckNameAvailabilityRequest.properties.type['x-ms-format'] = 'resource-type'; -``` diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/after/global.json b/tests/dotnet-upgrade/dotnet-aot-compat/after/global.json deleted file mode 100644 index 3be1c15acd..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/after/global.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "sdk": { - "version": "9.0.300", - "rollForward": "latestFeature" - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/.gitignore b/tests/dotnet-upgrade/dotnet-aot-compat/before/.gitignore deleted file mode 100644 index cd42ee34e8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -bin/ -obj/ diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmClient.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmClient.cs deleted file mode 100644 index 2993823501..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmClient.cs +++ /dev/null @@ -1,315 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups; -using Azure.ResourceManager.Resources; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager -{ - /// - /// The entry point for all ARM clients. - /// - public partial class ArmClient - { - private TenantResource _tenant; - private SubscriptionResource _defaultSubscription; - private readonly ClientDiagnostics _subscriptionClientDiagnostics; - private bool? _canUseTagResource; - - internal virtual Dictionary ApiVersionOverrides { get; } = new Dictionary(); - internal ConcurrentDictionary> ResourceApiVersionCache { get; } = new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase); - internal ConcurrentDictionary NamespaceVersionCache { get; } = new ConcurrentDictionary(); - - /// - /// Initializes a new instance of the class for mocking. - /// - protected ArmClient() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// A credential used to authenticate to an Azure Service. - /// If is null. -#pragma warning disable AZC0007 // DO provide a minimal constructor that takes only the parameters required to connect to the service. - public ArmClient(TokenCredential credential) : this(credential, default, default) -#pragma warning restore AZC0007 // DO provide a minimal constructor that takes only the parameters required to connect to the service. - { - } - - /// - /// Initializes a new instance of the class. - /// - /// A credential used to authenticate to an Azure Service. - /// The id of the default Azure subscription. - /// If is null. - public ArmClient(TokenCredential credential, string defaultSubscriptionId) : this(credential, defaultSubscriptionId, default) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// A credential used to authenticate to an Azure Service. - /// The id of the default Azure subscription. - /// The client parameters to use in these operations. - /// If is null. - public ArmClient(TokenCredential credential, string defaultSubscriptionId, ArmClientOptions options) - { - Argument.AssertNotNull(credential, nameof(credential)); - - options ??= new ArmClientOptions(); - ArmEnvironment environment = options.Environment.HasValue ? options.Environment.Value : ArmEnvironment.AzurePublicCloud; - - Argument.AssertNotNull(environment.Endpoint, nameof(environment.Endpoint)); - - Endpoint = environment.Endpoint; - - Pipeline = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(credential, environment.DefaultScope)); - - Diagnostics = options.Diagnostics; - _subscriptionClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager", SubscriptionResource.ResourceType.Namespace, Diagnostics); - - CopyApiVersionOverrides(options); - - _tenant = new TenantResource(this); - _defaultSubscription = string.IsNullOrWhiteSpace(defaultSubscriptionId) ? null : - new SubscriptionResource(this, SubscriptionResource.CreateResourceIdentifier(defaultSubscriptionId)); - } - - internal virtual bool CanUseTagResource(CancellationToken cancellationToken = default) - { - if (_canUseTagResource == null) - { - var tagRp = GetDefaultSubscription(cancellationToken).GetResourceProvider(TagResource.ResourceType.Namespace, cancellationToken: cancellationToken); - _canUseTagResource = tagRp.Value.Data.ResourceTypes.Any(rp => rp.ResourceType == TagResource.ResourceType.Type); - } - return _canUseTagResource.Value; - } - - internal virtual async Task CanUseTagResourceAsync(CancellationToken cancellationToken = default) - { - if (_canUseTagResource == null) - { - var tagRp = await GetDefaultSubscription(cancellationToken).GetResourceProviderAsync(TagResource.ResourceType.Namespace, cancellationToken: cancellationToken).ConfigureAwait(false); - _canUseTagResource = tagRp.Value.Data.ResourceTypes.Any(rp => rp.ResourceType == TagResource.ResourceType.Type); - } - return _canUseTagResource.Value; - } - - private void CopyApiVersionOverrides(ArmClientOptions options) - { - foreach (var keyValuePair in options.ResourceApiVersionOverrides) - { - ApiVersionOverrides.Add(keyValuePair.Key, keyValuePair.Value); - } - } - - /// - /// Gets the api version override if it has been set for the current client options. - /// - /// The resource type to get the version for. - /// The api version to variable to set. - internal virtual bool TryGetApiVersion(ResourceType resourceType, out string apiVersion) - { - return ApiVersionOverrides.TryGetValue(resourceType, out apiVersion); - } - - /// - /// Gets the diagnostic options used for this client. - /// - internal virtual DiagnosticsOptions Diagnostics { get; } - - /// - /// Gets the base URI of the service. - /// - internal virtual Uri Endpoint { get; private set; } - - /// - /// Gets the HTTP pipeline. - /// - internal virtual HttpPipeline Pipeline { get; private set; } - - /// - /// Gets the Azure subscriptions. - /// - /// Subscription collection. - public virtual SubscriptionCollection GetSubscriptions() => _tenant.GetSubscriptions(); - - /// - /// Gets the tenants. - /// - /// Tenant collection. - public virtual TenantCollection GetTenants() - { - return new TenantCollection(this); - } - - /// - /// Gets the default subscription. - /// - /// Resource operations of the Subscription. -#pragma warning disable AZC0015 // Unexpected client method return type. - public virtual SubscriptionResource GetDefaultSubscription(CancellationToken cancellationToken = default) -#pragma warning restore AZC0015 // Unexpected client method return type. - { - using var scope = _subscriptionClientDiagnostics.CreateScope("ArmClient.GetDefaultSubscription"); - scope.Start(); - try - { - if (_defaultSubscription == null) - { - _defaultSubscription = GetSubscriptions().GetAll(cancellationToken).FirstOrDefault(); - } - else if (_defaultSubscription.HasData) - { - return _defaultSubscription; - } - else - { - _defaultSubscription = _defaultSubscription.Get(cancellationToken); - } - if (_defaultSubscription is null) - { - throw new InvalidOperationException("No subscriptions found for the given credentials"); - } - return _defaultSubscription; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets the default subscription. - /// - /// Resource operations of the Subscription. -#pragma warning disable AZC0015 // Unexpected client method return type. - public virtual async Task GetDefaultSubscriptionAsync(CancellationToken cancellationToken = default) -#pragma warning restore AZC0015 // Unexpected client method return type. - { - using var scope = _subscriptionClientDiagnostics.CreateScope("ArmClient.GetDefaultSubscription"); - scope.Start(); - try - { - if (_defaultSubscription == null) - { - _defaultSubscription = await GetSubscriptions().GetAllAsync(cancellationToken).FirstOrDefaultAsync(_ => true, cancellationToken).ConfigureAwait(false); - } - else if (_defaultSubscription.HasData) - { - return _defaultSubscription; - } - else - { - _defaultSubscription = await _defaultSubscription.GetAsync(cancellationToken).ConfigureAwait(false); - } - if (_defaultSubscription is null) - { - throw new InvalidOperationException("No subscriptions found for the given credentials"); - } - return _defaultSubscription; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Gets a collection of GenericResources. - /// An object representing collection of GenericResources and their operations. - public virtual GenericResourceCollection GetGenericResources() => _tenant.GetGenericResources(); - - /// Gets all resource providers for a subscription. - /// [This parameter is no longer supported.] The number of results to return. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - [ForwardsClientCalls] - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("This method is obsolete as the `top` parameter is not supported by service and will be removed in a future release.", false)] - public virtual Pageable GetTenantResourceProviders(int? top, string expand, CancellationToken cancellationToken = default) => _tenant.GetTenantResourceProviders(expand, cancellationToken); - - /// Gets all resource providers for a subscription. - /// [This parameter is no longer supported.] The number of results to return. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - [ForwardsClientCalls] - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("This method is obsolete as the `top` parameter is not supported by service and will be removed in a future release.", false)] - public virtual AsyncPageable GetTenantResourceProvidersAsync(int? top, string expand, CancellationToken cancellationToken = default) => _tenant.GetTenantResourceProvidersAsync(expand, cancellationToken); - - /// Gets all resource providers for a subscription. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - [ForwardsClientCalls] - public virtual Pageable GetTenantResourceProviders(string expand = null, CancellationToken cancellationToken = default) => _tenant.GetTenantResourceProviders(expand, cancellationToken); - - /// Gets all resource providers for a subscription. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - [ForwardsClientCalls] - public virtual AsyncPageable GetTenantResourceProvidersAsync(string expand = null, CancellationToken cancellationToken = default) => _tenant.GetTenantResourceProvidersAsync(expand, cancellationToken); - - /// Gets the specified resource provider at the tenant level. - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - [ForwardsClientCalls] - public virtual Response GetTenantResourceProvider(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) => _tenant.GetTenantResourceProvider(resourceProviderNamespace, expand, cancellationToken); - - /// Gets the specified resource provider at the tenant level. - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - [ForwardsClientCalls] - public virtual async Task> GetTenantResourceProviderAsync(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) => await _tenant.GetTenantResourceProviderAsync(resourceProviderNamespace, expand, cancellationToken).ConfigureAwait(false); - - /// - /// Gets the management group collection for this tenant. - /// - /// A collection of the management groups. - public virtual ManagementGroupCollection GetManagementGroups() => _tenant.GetManagementGroups(); - - /// - /// Gets a client using this instance of ArmClient to copy the client settings from. - /// - /// The type of that will be constructed. - /// Delegate method that will construct the client. - [EditorBrowsable(EditorBrowsableState.Never)] - public virtual T GetResourceClient(Func resourceFactory) - where T : ArmResource - { - return resourceFactory(); - } - - private readonly ConcurrentDictionary _clientCache = new ConcurrentDictionary(); - - /// - /// Gets a cached client to use for extension methods. - /// - /// The type of client to get. - /// The constructor factory for the client. - [EditorBrowsable(EditorBrowsableState.Never)] - public virtual T GetCachedClient(Func clientFactory) - where T : class - { - return _clientCache.GetOrAdd(typeof(T), (type) => { return clientFactory(this); }) as T; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmClientOptions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmClientOptions.cs deleted file mode 100644 index dc9d5b6cc6..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmClientOptions.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Resources; -using Azure.ResourceManager; - -namespace Azure.ResourceManager -{ - /// - /// A class representing Azure resource manager client options. - /// -#pragma warning disable AZC0008 // ClientOptions should have a nested enum called ServiceVersion - public sealed class ArmClientOptions : ClientOptions -#pragma warning restore AZC0008 // ClientOptions should have a nested enum called ServiceVersion - { - internal IDictionary ResourceApiVersionOverrides { get; } = new Dictionary(); - - /// - /// Gets or sets Azure cloud environment. - /// - public ArmEnvironment? Environment { get; set; } - - /// - /// Sets the api version to use for a given resource type. - /// To find which API Versions are available in your environment you can use the method - /// for the provider namespace you are interested in. - /// - /// The resource type to set the version for. To determine the appropriate value, you can refer to the corresponding documentation or XML documentation comments of the API. Then, get its resource type from the Resource's ResourceType field. - /// The api version to use. - public void SetApiVersion(ResourceType resourceType, string apiVersion) - { - Argument.AssertNotNullOrEmpty(apiVersion, nameof(apiVersion)); - - ResourceApiVersionOverrides[resourceType] = apiVersion; - } - - /// - /// Sets the api versions from an Azure Stack profile. - /// - public void SetApiVersionsFromProfile(AzureStackProfile profile) - { - var assembly = Assembly.GetExecutingAssembly(); - using (Stream stream = assembly.GetManifestResourceStream(profile.GetManifestName())) - { - var span = BinaryData.FromStream(stream).ToMemory().Span; - var allProfile = JsonSerializer.Deserialize>>(span); - var armProfile = allProfile["resource-manager"]; - foreach (var keyValuePair in armProfile) - { - var namespaceName = keyValuePair.Key; - var element = keyValuePair.Value; - - foreach (var apiVersionProperty in element.EnumerateObject()) - { - var apiVersion = apiVersionProperty.Name; - foreach (var resourceTypeItem in apiVersionProperty.Value.EnumerateArray()) - { - string resourceTypeName = default; - foreach (var property in resourceTypeItem.EnumerateObject()) - { - if (property.NameEquals("resourceType")) - { - resourceTypeName = property.Value.GetString(); - break; - } - } - var resourceType = $"{namespaceName}/{resourceTypeName}"; - ResourceApiVersionOverrides[resourceType] = apiVersion; - } - } - } - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmCollection.cs deleted file mode 100644 index c3b5b1b084..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmCollection.cs +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Collections.Concurrent; -using System.ComponentModel; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager -{ - /// - /// Base class representing collection of resources. - /// - public abstract class ArmCollection - { - private readonly ConcurrentDictionary _clientCache = new ConcurrentDictionary(); - - /// - /// Initializes a new instance of the class for mocking. - /// - protected ArmCollection() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The client to copy settings from. - /// The id of the parent for the collection. - protected ArmCollection(ArmClient client, ResourceIdentifier id) - { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(client, nameof(client)); - - Client = client; - Id = id; - } - - /// - /// Gets the resource identifier. - /// - public virtual ResourceIdentifier Id { get; } - - /// - /// Gets the this resource client was created from. - /// - protected internal virtual ArmClient Client { get; } - - /// - /// Gets the diagnostic options for this resource client. - /// - protected internal DiagnosticsOptions Diagnostics => Client.Diagnostics; - - /// - /// Gets the pipeline for this resource client. - /// - protected internal HttpPipeline Pipeline => Client.Pipeline; - - /// - /// Gets the base uri for this resource client. - /// - protected internal Uri Endpoint => Client.Endpoint; - - /// - /// Gets the api version override if it has been set for the current client options. - /// - /// The resource type to get the version for. - /// The api version to variable to set. - protected bool TryGetApiVersion(ResourceType resourceType, out string apiVersion) => Client.TryGetApiVersion(resourceType, out apiVersion); - - /// - /// Gets a cached client to use for extension methods. - /// - /// The type of client to get. - /// The constructor factory for the client. - [EditorBrowsable(EditorBrowsableState.Never)] - public virtual T GetCachedClient(Func clientFactory) - where T : class - { - return _clientCache.GetOrAdd(typeof(T), (type) => { return clientFactory(Client); }) as T; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmEnvironment.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmEnvironment.cs deleted file mode 100644 index cc8fe784fb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmEnvironment.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Text.Json; -using System.ComponentModel; -using Azure.Core; - -namespace Azure.ResourceManager -{ - /// - /// ArmEnvrionment represents the information of an Azure Cloud environment. - /// - public readonly struct ArmEnvironment : IEquatable - { - // name after the `name` property of returned audience from https://management.azure.com/metadata/endpoints?api-version=2019-11-01 - /// Azure Public Cloud. - public static readonly ArmEnvironment AzurePublicCloud = new(new Uri("https://management.azure.com"), "https://management.azure.com/"); - - /// Azure China Cloud. - public static readonly ArmEnvironment AzureChina = new(new Uri("https://management.chinacloudapi.cn"), "https://management.chinacloudapi.cn"); - - /// Azure US Government. - public static readonly ArmEnvironment AzureGovernment = new(new Uri("https://management.usgovcloudapi.net"), "https://management.usgovcloudapi.net"); - - /// Azure German Cloud. - public static readonly ArmEnvironment AzureGermany = new(new Uri("https://management.microsoftazure.de"), "https://management.microsoftazure.de"); - - /// - /// Gets base URI of the management API endpoint. - /// - public readonly Uri Endpoint { get; } - - /// - /// Gets authentication audience. - /// - public readonly string Audience { get; } - - /// - /// Gets default authentication scope. - /// - public string DefaultScope { get; } - - /// - /// Construct an using the given value. - /// - /// Management API endpoint base URI. - /// Authentication audience. - public ArmEnvironment(Uri endpoint, string audience) - { - Argument.AssertNotNull(endpoint, nameof(endpoint)); - Argument.AssertNotNullOrWhiteSpace(audience, nameof(audience)); - - Endpoint = endpoint; - Audience = audience; - DefaultScope = $"{Audience}/.default"; - } - - /// Determines if two values are the same. - public static bool operator ==(ArmEnvironment left, ArmEnvironment right) => left.Equals(right); - - /// Determines if two values are not the same. internal - public static bool operator !=(ArmEnvironment left, ArmEnvironment right) => !left.Equals(right); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ArmEnvironment other && Equals(other); - - /// - public bool Equals(ArmEnvironment other) => string.Equals(Audience, other.Audience, StringComparison.Ordinal) && Endpoint.Equals(other.Endpoint); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() - { - return HashCodeBuilder.Combine(Endpoint, Audience); - } - - /// - public override string ToString() => JsonSerializer.Serialize(this); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmOperation.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmOperation.cs deleted file mode 100644 index 363ed99fff..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmOperation.cs +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.ClientModel.Primitives; -using System.Reflection; -using System; -using Azure.Core; -using Azure.Core.Pipeline; -using System.Threading.Tasks; - -namespace Azure.ResourceManager -{ - /// - public abstract class ArmOperation : Operation - { - /// - /// Rehydrates an operation from a . - /// - /// The Arm client. - /// The rehydration token. - /// The Arm client options. - /// The long-running operation. - public static ArmOperation Rehydrate(ArmClient client, RehydrationToken rehydrationToken, ArmClientOptions options = null) - { - Argument.AssertNotNull(client, nameof(client)); - Argument.AssertNotNull(rehydrationToken, nameof(rehydrationToken)); - - var nextLinkOperation = (NextLinkOperationImplementation)NextLinkOperationImplementation.Create(client.Pipeline, rehydrationToken); - var operationState = nextLinkOperation.UpdateStateAsync(async: false, default).EnsureCompleted(); - return new RehydrationOperation(nextLinkOperation, operationState); - } - - /// - /// Rehydrates an operation from a . - /// - /// The Arm client. - /// The rehydration token. - /// The Arm client options. - /// The long-running operation. - public static ArmOperation Rehydrate(ArmClient client, RehydrationToken rehydrationToken, ArmClientOptions options = null) where T : notnull - { - - Argument.AssertNotNull(client, nameof(client)); - Argument.AssertNotNull(rehydrationToken, nameof(rehydrationToken)); - - bool isResource = IsResource(); - IOperationSource source = new GenericOperationSource(client, isResource); - var nextLinkOperation = (NextLinkOperationImplementation)NextLinkOperationImplementation.Create(client.Pipeline, rehydrationToken); - var operation = NextLinkOperationImplementation.Create(source, nextLinkOperation); - var operationState = operation.UpdateStateAsync(async: false, default).EnsureCompleted(); - return new RehydrationOperation(nextLinkOperation, operationState, operation, options); - } - - /// - /// Rehydrates an operation from a . - /// - /// The Arm client. - /// The rehydration token. - /// The Arm client options. - /// The long-running operation. - public static async Task RehydrateAsync(ArmClient client, RehydrationToken rehydrationToken, ArmClientOptions options = null) - { - Argument.AssertNotNull(client, nameof(client)); - Argument.AssertNotNull(rehydrationToken, nameof(rehydrationToken)); - - var nextLinkOperation = (NextLinkOperationImplementation)NextLinkOperationImplementation.Create(client.Pipeline, rehydrationToken); - var operationState = await nextLinkOperation.UpdateStateAsync(async: true, default).ConfigureAwait(false); - return new RehydrationOperation(nextLinkOperation, operationState); - } - - /// - /// Rehydrates an operation from a . - /// - /// The Arm client. - /// The rehydration token. - /// The Arm client options. - /// The long-running operation. - public static async Task> RehydrateAsync(ArmClient client, RehydrationToken rehydrationToken, ArmClientOptions options = null) where T : notnull - { - - Argument.AssertNotNull(client, nameof(client)); - Argument.AssertNotNull(rehydrationToken, nameof(rehydrationToken)); - - bool isResource = IsResource(); - IOperationSource source = new GenericOperationSource(client, isResource); - var nextLinkOperation = (NextLinkOperationImplementation)NextLinkOperationImplementation.Create(client.Pipeline, rehydrationToken); - var operation = NextLinkOperationImplementation.Create(source, nextLinkOperation); - var operationState = await operation.UpdateStateAsync(async: true, default).ConfigureAwait(false); - return new RehydrationOperation(nextLinkOperation, operationState, operation, options); - } - - private static bool IsResource() where T : notnull - { - var isResource = typeof(T).GetConstructor( - BindingFlags.NonPublic | BindingFlags.Instance, - null, - CallingConventions.Any, - new Type[] { typeof(ArmClient), typeof(ResourceIdentifier) }, - null) is not null; - var obj = Activator.CreateInstance(typeof(T), BindingFlags.NonPublic | BindingFlags.Instance, null, null, null); - if (!isResource && obj is not IJsonModel) - { - throw new InvalidOperationException($"Type {typeof(T)} should be Resource or Model"); - } - - return isResource; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmOperationOfT.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmOperationOfT.cs deleted file mode 100644 index 5b23a5d6a7..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmOperationOfT.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - - -namespace Azure.ResourceManager -{ - /// - public abstract class ArmOperation : Operation - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmResource.cs deleted file mode 100644 index 3e5e82e19b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ArmResource.cs +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager -{ - /// - /// A class representing the operations that can be performed over a specific resource. - /// - public abstract partial class ArmResource - { - private readonly ConcurrentDictionary _clientCache = new ConcurrentDictionary(); - - /// - /// Initializes a new instance of the class for mocking. - /// - protected ArmResource() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The this resource client should be created from. - /// The identifier of the resource that is the target of operations. - protected internal ArmResource(ArmClient client, ResourceIdentifier id) - { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(client, nameof(client)); - - Client = client; - Id = id; - } - - /// - /// Gets the resource identifier. - /// - public virtual ResourceIdentifier Id { get; } - - /// - /// Gets the this resource client was created from. - /// - protected internal virtual ArmClient Client { get; } - - /// - /// Gets the diagnostic options for this resource client. - /// - protected internal DiagnosticsOptions Diagnostics => Client.Diagnostics; - - /// - /// Gets the pipeline for this resource client. - /// - protected internal HttpPipeline Pipeline => Client.Pipeline; - - /// - /// Gets the base uri for this resource client. - /// - protected internal Uri Endpoint => Client.Endpoint; - - /// - /// Gets the api version override if it has been set for the current client options. - /// - /// The resource type to get the version for. - /// The api version to variable to set. - protected virtual bool TryGetApiVersion(ResourceType resourceType, out string apiVersion) => Client.TryGetApiVersion(resourceType, out apiVersion); - - /// - /// Lists all available geo-locations. - /// - /// A token to allow the caller to cancel the call to the service. The default value is . - /// A collection of location that may take multiple service requests to iterate over. - [ForwardsClientCalls] - public virtual Response> GetAvailableLocations(CancellationToken cancellationToken = default) - { - string nameSpace = Id.ResourceType.Namespace; - string type = Id.ResourceType.Type; - Response resourcePageableProviderResponse = Client.GetTenantResourceProvider(nameSpace, null, cancellationToken); - TenantResourceProvider resourcePageableProvider = resourcePageableProviderResponse.Value; - if (resourcePageableProvider is null) - throw new InvalidOperationException($"{type} not found for {nameSpace}"); - var theResource = resourcePageableProvider.ResourceTypes.FirstOrDefault(r => type.Equals(r.ResourceType, StringComparison.Ordinal)); - if (theResource is null) - throw new InvalidOperationException($"{type} not found for {nameSpace}"); - return Response.FromValue(theResource.Locations.Select(l => new AzureLocation(l)), resourcePageableProviderResponse.GetRawResponse()); - } - - /// - /// Lists all available geo-locations. - /// - /// A token to allow the caller to cancel the call to the service. The default value is . - /// A collection of location that may take multiple service requests to iterate over. - [ForwardsClientCalls] - public virtual async Task>> GetAvailableLocationsAsync(CancellationToken cancellationToken = default) - { - string nameSpace = Id.ResourceType.Namespace; - string type = Id.ResourceType.Type; - Response resourcePageableProviderResponse = await Client.GetTenantResourceProviderAsync(nameSpace, null, cancellationToken).ConfigureAwait(false); - TenantResourceProvider resourcePageableProvider = resourcePageableProviderResponse.Value; - if (resourcePageableProvider is null) - throw new InvalidOperationException($"{type} not found for {nameSpace}"); - var theResource = resourcePageableProvider.ResourceTypes.FirstOrDefault(r => type.Equals(r.ResourceType, StringComparison.Ordinal)); - if (theResource is null) - throw new InvalidOperationException($"{type} not found for {nameSpace}"); - return Response.FromValue(theResource.Locations.Select(l => new AzureLocation(l)), resourcePageableProviderResponse.GetRawResponse()); - } - - /// - /// Gets a cached client to use for extension methods. - /// - /// The type of client to get. - /// The constructor factory for the client. - [EditorBrowsable(EditorBrowsableState.Never)] - public virtual T GetCachedClient(Func clientFactory) - where T : class - { - return _clientCache.GetOrAdd(typeof(T), (type) => { return clientFactory(Client); }) as T; - } - - /// - /// Checks to see if the TagResource API is deployed in the current environment. - /// - protected virtual bool CanUseTagResource(CancellationToken cancellationToken = default) => Client.CanUseTagResource(cancellationToken); - - /// - /// Checks to see if the TagResource API is deployed in the current environment. - /// - protected virtual Task CanUseTagResourceAsync(CancellationToken cancellationToken = default) => Client.CanUseTagResourceAsync(cancellationToken); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Assets/Profile/2020-09-01-hybrid.json b/tests/dotnet-upgrade/dotnet-aot-compat/before/Assets/Profile/2020-09-01-hybrid.json deleted file mode 100644 index d19b2f0667..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Assets/Profile/2020-09-01-hybrid.json +++ /dev/null @@ -1,678 +0,0 @@ -{ - "info": { - "name": "2020-09-01-hybrid", - "description": "Profile definition targeted for hybrid applications that could run on azure stack general availability version and azure cloud for 2010." - }, - "resource-manager": { - "microsoft.authorization": { - "2016-09-01": [ - { - "resourceType": "locks", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Authorization/stable/2016-09-01/locks.json" - } - ], - "2016-12-01": [ - { - "resourceType": "policyAssignments", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Authorization/stable/2016-12-01/policyAssignments.json" - }, - { - "resourceType": "policyDefinitions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Authorization/stable/2016-12-01/policyDefinitions.json" - } - ], - "2015-07-01": [ - { - "resourceType": "permissions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/authorization/resource-manager/Microsoft.Authorization/stable/2015-07-01/authorization-ClassicAdminCalls.json" - }, - { - "resourceType": "roleAssignments", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/authorization/resource-manager/Microsoft.Authorization/stable/2015-07-01/authorization-RoleAssignmentsCalls.json" - }, - { - "resourceType": "roleDefinitions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/authorization/resource-manager/Microsoft.Authorization/stable/2015-07-01/authorization-RoleDefinitionsCalls.json" - }, - { - "resourceType": "providerOperations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/authorization/resource-manager/Microsoft.Authorization/stable/2015-07-01/authorization-ProviderOperationsCalls.json" - } - ] - }, - "microsoft.commerce": { - "2015-06-01-preview": [ - { - "resourceType": "estimateResourceSpend", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/commerce/resource-manager/Microsoft.Commerce/preview/2015-06-01-preview/commerce.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/commerce/resource-manager/Microsoft.Commerce/preview/2015-06-01-preview/commerce.json" - }, - { - "resourceType": "subscriberUsageAggregates", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/commerce/resource-manager/Microsoft.Commerce/preview/2015-06-01-preview/commerce.json" - }, - { - "resourceType": "usageAggregates", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/commerce/resource-manager/Microsoft.Commerce/preview/2015-06-01-preview/commerce.json" - } - ] - }, - "microsoft.compute": { - "2020-06-01": [ - { - "resourceType": "availabilitySets", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "images", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "locations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "locations/publishers", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "locations/operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "locations/usages", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "locations/vmSizes", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "virtualMachines", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "virtualMachines/extensions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "virtualMachineScaleSets", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "virtualMachineScaleSets/extensions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "virtualmachineScaleSets/networkInterfaces", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "virtualMachineScaleSets/virtualMachines", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - }, - { - "resourceType": "virtualMachineScaleSets/virtualMachines/networkInterfaces", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2020-06-01/compute.json" - } - ], - "2019-07-01": [ - { - "resourceType": "disks", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2019-07-01/disk.json" - }, - { - "resourceType": "snapshots", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/compute/resource-manager/Microsoft.Compute/stable/2019-07-01/disk.json" - } - ] - }, - "microsoft.databoxedge": { - "2019-08-01": [ - { - "resourceType": "dataBoxEdgeDevices", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/databoxedge/resource-manager/Microsoft.DataBoxEdge/stable/2019-08-01/databoxedge.json" - }, - { - "resourceType": "dataBoxEdgeDevices/checkNameAvailability", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/databoxedge/resource-manager/Microsoft.DataBoxEdge/stable/2019-08-01/databoxedge.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/databoxedge/resource-manager/Microsoft.DataBoxEdge/stable/2019-08-01/databoxedge.json" - } - ] - }, - "microsoft.devices": { - "2019-07-01-preview": [ - { - "resourceType": "usages", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - }, - { - "resourceType": "locations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - }, - { - "resourceType": "locations/quotas", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - }, - { - "resourceType": "locations/skus", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - }, - { - "resourceType": "checkNameAvailability", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - }, - { - "resourceType": "operationResults", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - }, - { - "resourceType": "IotHubs", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - }, - { - "resourceType": "backupProviders", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - }, - { - "resourceType": "backupProviders/operationResults", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/preview/2019-07-01-preview/iothub.json" - } - ] - }, - "microsoft.eventhubs": { - "2018-01-01-preview": [ - { - "resourceType": "availableClusterRegions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/preview/2018-01-01-preview/AvailableClusterRegions-preview.json" - }, - { - "resourceType": "clusters", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/preview/2018-01-01-preview/Clusters-preview.json" - }, - { - "resourceType": "namespaces", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/preview/2018-01-01-preview/namespaces-preview.json" - } - ], - "2017-04-01": [ - { - "resourceType": "checkNameAvailability", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/stable/2017-04-01/CheckNameAvailability.json" - }, - { - "resourceType": "namespaces/authorizationRules", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/stable/2017-04-01/AuthorizationRules.json" - }, - { - "resourceType": "namespaces/eventhubs", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/stable/2017-04-01/eventhubs.json" - }, - { - "resourceType": "namespaces/eventhubs/authorizationRules", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/stable/2017-04-01/AuthorizationRules.json" - }, - { - "resourceType": "namespaces/eventhubs/consumerGroups", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/stable/2017-04-01/consumergroups.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/stable/2017-04-01/operations.json" - }, - { - "resourceType": "sku", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/eventhub/resource-manager/Microsoft.EventHub/stable/2017-04-01/sku.json" - } - ] - }, - "microsoft.insights": { - "2018-01-01": [ - { - "resourceType": "metricDefinitions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/monitor/resource-manager/Microsoft.Insights/stable/2018-01-01/metricDefinitions_API.json" - }, - { - "resourceType": "metrics", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/monitor/resource-manager/Microsoft.Insights/stable/2018-01-01/metrics_API.json" - } - ], - "2017-05-01-preview": [ - { - "resourceType": "diagnosticSettings", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/monitor/resource-manager/Microsoft.Insights/preview/2017-05-01-preview/diagnosticsSettings_API.json" - }, - { - "resourceType": "diagnosticSettingCategories", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/monitor/resource-manager/Microsoft.Insights/preview/2017-05-01-preview/diagnosticsSettingsCategories_API.json" - } - ], - "2015-04-01": [ - { - "resourceType": "eventCategories", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/monitor/resource-manager/Microsoft.Insights/stable/2015-04-01/eventCategories_API.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/monitor/resource-manager/Microsoft.Insights/stable/2015-04-01/operations_API.json" - } - ] - }, - "microsoft.keyvault": { - "2019-09-01": [ - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/keyvault/resource-manager/Microsoft.KeyVault/stable/2019-09-01/providers.json" - }, - { - "resourceType": "vaults", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/keyvault/resource-manager/Microsoft.KeyVault/stable/2019-09-01/keyvault.json" - }, - { - "resourceType": "vaults/accessPolicies", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/keyvault/resource-manager/Microsoft.KeyVault/stable/2019-09-01/keyvault.json" - }, - { - "resourceType": "vaults/secrets", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/keyvault/resource-manager/Microsoft.KeyVault/stable/2019-09-01/secrets.json" - } - ] - }, - "microsoft.network": { - "2018-11-01": [ - { - "resourceType": "connections", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/virtualNetworkGateway.json" - }, - { - "resourceType": "loadBalancers", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/loadBalancer.json" - }, - { - "resourceType": "localNetworkGateways", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/virtualNetworkGateway.json" - }, - { - "resourceType": "locations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/network.json" - }, - { - "resourceType": "locations/operationResults", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/network.json" - }, - { - "resourceType": "locations/operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/network.json" - }, - { - "resourceType": "locations/usages", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/network.json" - }, - { - "resourceType": "networkInterfaces", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/networkInterface.json" - }, - { - "resourceType": "networkSecurityGroups", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/networkSecurityGroup.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/operation.json" - }, - { - "resourceType": "publicIpAddresses", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/publicIpAddress.json" - }, - { - "resourceType": "routeTables", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/routeTable.json" - }, - { - "resourceType": "virtualNetworkGateways", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/virtualNetworkGateway.json" - }, - { - "resourceType": "virtualNetworks", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/network/resource-manager/Microsoft.Network/stable/2018-11-01/virtualNetwork.json" - } - ], - "2016-04-01": [ - { - "resourceType": "dnsZones", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/dns/resource-manager/Microsoft.Network/stable/2016-04-01/dns.json" - } - ] - }, - "microsoft.resources": { - "2016-06-01": [ - { - "resourceType": "subscriptions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2016-06-01/subscriptions.json" - }, - { - "resourceType": "subscriptions/locations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2016-06-01/subscriptions.json" - }, - { - "resourceType": "tenants", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2016-06-01/subscriptions.json" - } - ], - "2019-10-01": [ - { - "resourceType": "deployments", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "deployments/operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "links", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "locations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "providers", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "resourceGroups", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "resources", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "subscriptions/operationresults", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "subscriptions/providers", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "subscriptions/resourceGroups", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "subscriptions/resourceGroups/resources", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "subscriptions/resources", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "subscriptions/tagNames", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - }, - { - "resourceType": "subscriptions/tagNames/tagValues", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/resources/resource-manager/Microsoft.Resources/stable/2019-10-01/resources.json" - } - ] - }, - "microsoft.storage": { - "2019-06-01": [ - { - "resourceType": "checkNameAvailability", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/storage.json" - }, - { - "resourceType": "locations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/storage.json" - }, - { - "resourceType": "locations/quotas", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/storage.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/storage.json" - }, - { - "resourceType": "storageAccounts", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/storage.json" - }, - { - "resourceType": "storageAccounts/blobServices", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/storage.json" - }, - { - "resourceType": "storageAccounts/queueServices", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/storage.json" - }, - { - "resourceType": "storageAccounts/tableServices", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/storage.json" - }, - { - "resourceType": "usages", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/storage.json" - } - ] - }, - "microsoft.web": { - "2018-02-01": [ - { - "resourceType": "certificates", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/Certificates.json" - }, - { - "resourceType": "operations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "checknameavailability", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/ResourceProvider.json" - }, - { - "resourceType": "metadata", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites/domainOwnershipIdentifiers", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites/extensions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites/hostNameBindings", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites/instances", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites/instances/extensions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites/slots", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites/slots/hostNameBindings", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites/slots/instances", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "sites/slots/instances/extensions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "serverFarms", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/WebApps.json" - }, - { - "resourceType": "serverFarms/metricDefinitions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/AppServicePlans.json" - }, - { - "resourceType": "serverFarms/metrics", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/AppServicePlans.json" - }, - { - "resourceType": "serverFarms/usages", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/AppServicePlans.json" - }, - { - "resourceType": "availableStacks", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/Provider.json" - }, - { - "resourceType": "deploymentLocations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/ResourceProvider.json" - }, - { - "resourceType": "georegions", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/ResourceProvider.json" - }, - { - "resourceType": "listSitesAssignedToHostName", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/ResourceProvider.json" - }, - { - "resourceType": "publishingUsers", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/ResourceProvider.json" - }, - { - "resourceType": "recommendations", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/Recommendations.json" - }, - { - "resourceType": "sourceControls", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/ResourceProvider.json" - }, - { - "resourceType": "validate", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/web/resource-manager/Microsoft.Web/stable/2018-02-01/ResourceProvider.json" - } - ] - }, - "microsoft.containerregistry" : { - "2019-05-01": [ - { - "resourceType": "registries", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - }, - { - "resourceType": "registries/importImage", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - }, - { - "resourceType": "registries/webhooks", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - }, - { - "resourceType": "registries/webhooks/ping", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - }, - { - "resourceType": "registries/webhooks/getCallbackConfig", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - }, - { - "resourceType": "registries/webhooks/listEvents", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - }, - { - "resourceType": "registries/listCredentials", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - }, - { - "resourceType": "registries/regenerateCredential", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - }, - { - "resourceType": "checkNameAvailability", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - }, - { - "resourceType": "operations", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/resource-manager/Microsoft.ContainerRegistry/stable/2019-05-01/containerregistry.json" - } - ] - }, - "microsoft.containerservice" : { - "2020-11-01": [ - { - "resourceType": "managedclusters", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerservice/resource-manager/Microsoft.ContainerService/stable/2020-11-01/managedClusters.json" - } - ], - "2019-04-01": [ - { - "resourceType": "locations/orchestrators", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerservice/resource-manager/Microsoft.ContainerService/stable/2019-04-01/location.json" - } - ], - "2017-07-01": [ - { - "resourceType": "containerServices", - "path" : "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerservice/resource-manager/Microsoft.ContainerService/stable/2017-07-01/containerService.json" - } - ] - } - }, - "data-plane": { - "microsoft.keyvault": { - "7.1": [ - { - "resourceType": "secrets", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/keyvault/data-plane/Microsoft.KeyVault/stable/7.1/secrets.json" - }, - { - "resourceType": "keys", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/keyvault/data-plane/Microsoft.KeyVault/stable/7.1/keys.json" - } - ] - }, - "microsoft.containerregistry": { - "2019-08-15-preview": [ - { - "resourceType": "*", - "path": "https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/containerregistry/data-plane/Microsoft.ContainerRegistry/preview/2019-08-15/containerregistry.json" - } - ] - }, - "microsoft.storage": { - "resourceType": "*", - "2019-07-07": [] - } - } - } diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Azure.ResourceManager.csproj b/tests/dotnet-upgrade/dotnet-aot-compat/before/Azure.ResourceManager.csproj deleted file mode 100644 index eed99d9d6d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Azure.ResourceManager.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - net9.0 - 1.14.0-beta.1 - - 1.13.1 - Azure.ResourceManager - Microsoft Azure Resource Manager client SDK for Azure resources. - azure;management;resource - true - false - false - $(NoWarn);AZPROVISION001;SCM0005 - - - - - - - - - - - - - - - - diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/AzureStackProfile.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/AzureStackProfile.cs deleted file mode 100644 index 09f285c061..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/AzureStackProfile.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -namespace Azure.ResourceManager -{ - /// - /// AzureStackProfile represents the information of an Azure Stack profile. - /// - public enum AzureStackProfile - { - /// The 2020-09-01-hybrid profile. - Profile20200901Hybrid - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/BicepModelReaderWriterOptions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/BicepModelReaderWriterOptions.cs deleted file mode 100644 index eaa886e500..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/BicepModelReaderWriterOptions.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; - -namespace Azure.ResourceManager -{ - /// - /// Provides the options for reading and writing Bicep. - /// - [Experimental("AZPROVISION001")] - public class BicepModelReaderWriterOptions : ModelReaderWriterOptions - { - /// - /// Initializes a new instance of . - /// - public BicepModelReaderWriterOptions() : base("bicep") - { - } - - /// - /// The set of property overrides to apply when writing the bicep. The key of the dictionary corresponds to the - /// instance being written, and the value is a dictionary of property names to property values. - /// - public IDictionary> PropertyOverrides { get; } = new Dictionary>(); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/CodeGenAttributes.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/CodeGenAttributes.cs deleted file mode 100644 index efc951c129..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/CodeGenAttributes.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Stubs for Azure AutoRest codegen types (not available as a public NuGet package) -#nullable enable - -// GeneratorPageableHelpers is a codegen-emitted copy of PageableHelpers -namespace Azure.Core -{ - internal static class GeneratorPageableHelpers - { - public static AsyncPageable CreateAsyncPageable( - System.Func? createFirstPageRequest, - System.Func? createNextPageRequest, - System.Func valueFactory, - Pipeline.ClientDiagnostics clientDiagnostics, - Pipeline.HttpPipeline pipeline, - string scopeName, - string? itemPropertyName, - string? nextLinkPropertyName, - System.Threading.CancellationToken cancellationToken) where T : notnull - => PageableHelpers.CreateAsyncPageable(createFirstPageRequest, createNextPageRequest, valueFactory, clientDiagnostics, pipeline, scopeName, itemPropertyName, nextLinkPropertyName, cancellationToken); - - public static Pageable CreatePageable( - System.Func? createFirstPageRequest, - System.Func? createNextPageRequest, - System.Func valueFactory, - Pipeline.ClientDiagnostics clientDiagnostics, - Pipeline.HttpPipeline pipeline, - string scopeName, - string? itemPropertyName, - string? nextLinkPropertyName, - System.Threading.CancellationToken cancellationToken) where T : notnull - => PageableHelpers.CreatePageable(createFirstPageRequest, createNextPageRequest, valueFactory, clientDiagnostics, pipeline, scopeName, itemPropertyName, nextLinkPropertyName, cancellationToken); - } - - [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct)] - internal class CodeGenTypeAttribute : System.Attribute - { - public CodeGenTypeAttribute(string originalName) { } - } - - [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct, AllowMultiple = true)] - internal class CodeGenSuppressAttribute : System.Attribute - { - public CodeGenSuppressAttribute(string member, params System.Type[] parameters) { } - } - - [System.AttributeUsage(System.AttributeTargets.Assembly, AllowMultiple = true)] - internal class CodeGenSuppressTypeAttribute : System.Attribute - { - public CodeGenSuppressTypeAttribute(string typeName) { } - } - - [System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Field, AllowMultiple = true)] - internal class CodeGenMemberAttribute : System.Attribute - { - public CodeGenMemberAttribute(string originalName) { } - } - - [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct, AllowMultiple = true)] - internal class CodeGenSerializationAttribute : System.Attribute - { - public CodeGenSerializationAttribute(string propertyName) { } - public string? SerializationValueHook { get; set; } - public string? DeserializationValueHook { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ArmPlan.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ArmPlan.cs deleted file mode 100644 index 35564305f8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ArmPlan.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.ComponentModel; -using System.Globalization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// - /// Representation of a publisher plan for marketplace RPs. - /// - public sealed partial class ArmPlan : IEquatable - { - /// - /// Compares this instance with another object and determines if they are equals. - /// - /// object to compare. - /// True if they are equals, otherwise false. - public bool Equals(ArmPlan other) - { - if (ReferenceEquals(other, null)) - return false; - - if (ReferenceEquals(this, other)) - return true; - - return string.Equals(Name, other.Name, StringComparison.InvariantCultureIgnoreCase) && - string.Equals(Product, other.Product, StringComparison.InvariantCultureIgnoreCase) && - string.Equals(PromotionCode, other.PromotionCode, StringComparison.InvariantCultureIgnoreCase) && - string.Equals(Publisher, other.Publisher, StringComparison.InvariantCultureIgnoreCase) && - string.Equals(Version, other.Version, StringComparison.InvariantCultureIgnoreCase); - } - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) - { - if (ReferenceEquals(this, obj)) - { - return true; - } - - if (ReferenceEquals(obj, null)) - { - return false; - } - - if (obj is not ArmPlan other) - return false; - - return Equals(other); - } - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() - { - return HashCodeBuilder.Combine( - Name?.ToLower(CultureInfo.InvariantCulture), - Publisher?.ToLower(CultureInfo.InvariantCulture), - Product?.ToLower(CultureInfo.InvariantCulture), - PromotionCode?.ToLower(CultureInfo.InvariantCulture), - Version?.ToLower(CultureInfo.InvariantCulture)); - } - - /// - /// Compares this instance with another object and determines if they are equals. - /// - /// The object on the left side of the operator. - /// The object on the right side of the operator. - /// True if they are equal, otherwise false. - public static bool operator ==(ArmPlan left, ArmPlan right) - { - if (ReferenceEquals(left, null)) - { - return ReferenceEquals(right, null); - } - - return left.Equals(right); - } - - /// - /// Compares this instance with another object and determines if they are equals. - /// - /// The object on the left side of the operator. - /// The object on the right side of the operator. - /// True if they are not equal, otherwise false. - public static bool operator !=(ArmPlan left, ArmPlan right) - { - return !(left == right); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ArmSku.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ArmSku.cs deleted file mode 100644 index ce20416eb1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ArmSku.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.ComponentModel; -using System.Globalization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// - /// A class representing SKU for resource. - /// - public sealed partial class ArmSku : IEquatable - { - /// - /// Compares this instance with another object and determines if they are equals. - /// - /// object to compare. - /// True if they are equals, otherwise false. - public bool Equals(ArmSku other) - { - if (other == null) - return false; - - if (object.ReferenceEquals(this, other)) - return true; - - return string.Equals(Name, other.Name, StringComparison.InvariantCultureIgnoreCase) && - string.Equals(Family, other.Family, StringComparison.InvariantCultureIgnoreCase) && - string.Equals(Size, other.Size, StringComparison.InvariantCultureIgnoreCase) && - (Tier.HasValue ? Tier.Value.Equals(other.Tier) : !other.Tier.HasValue) && - long.Equals(Capacity, other.Capacity); - } - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) - { - if (ReferenceEquals(this, obj)) - { - return true; - } - - if (ReferenceEquals(obj, null)) - { - return false; - } - - if (obj is not ArmSku other) - return false; - - return Equals(other); - } - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() - { - return HashCodeBuilder.Combine( - Name?.ToLower(CultureInfo.InvariantCulture), - Family?.ToLower(CultureInfo.InvariantCulture), - Size?.ToLower(CultureInfo.InvariantCulture), - Tier?.ToString().ToLower(CultureInfo.InvariantCulture), - Capacity); - } - - /// - /// Compares this instance with another object and determines if they are equals. - /// - /// The sku on the left side of the operator. - /// The sku on the right side of the operator. - /// True if they are equal, otherwise false. - public static bool operator ==(ArmSku left, ArmSku right) - { - if (ReferenceEquals(left, null)) - { - return ReferenceEquals(right, null); - } - - return left.Equals(right); - } - - /// - /// Compares this instance with another object and determines if they are not equal. - /// - /// The sku on the left side of the operator. - /// The sku on the right side of the operator. - /// True if they are not equal, otherwise false. - public static bool operator !=(ArmSku left, ArmSku right) - { - return !(left == right); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/EncryptionProperties.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/EncryptionProperties.cs deleted file mode 100644 index a5a35be565..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/EncryptionProperties.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Models -{ - // this class here is to keep the class public and add the EditorBrowsableNever attribute - // this class is exposed in resourcemanager by accident, now we hide it in resourcemanager - [Obsolete("This type is obsolete and will be removed in a future release.", false)] - [EditorBrowsable(EditorBrowsableState.Never)] - public partial class EncryptionProperties - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/EncryptionStatus.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/EncryptionStatus.cs deleted file mode 100644 index c1fc8e2bbc..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/EncryptionStatus.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Models -{ - // this class here is to keep the class public and add the EditorBrowsableNever attribute - // this class is exposed in resourcemanager by accident, now we hide it in resourcemanager - [Obsolete("This type is obsolete and will be removed in a future release.", false)] - [EditorBrowsable(EditorBrowsableState.Never)] - public readonly partial struct EncryptionStatus - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/KeyVaultProperties.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/KeyVaultProperties.cs deleted file mode 100644 index 5b49b0341a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/KeyVaultProperties.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Models -{ - // this class here is to keep the class public and add the EditorBrowsableNever attribute - // this class is exposed in resourcemanager by accident, now we hide it in resourcemanager - [Obsolete("This type is obsolete and will be removed in a future release.", false)] - [EditorBrowsable(EditorBrowsableState.Never)] - public partial class KeyVaultProperties - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentity.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentity.Serialization.cs deleted file mode 100644 index 470061ab7d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentity.Serialization.cs +++ /dev/null @@ -1,263 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; -using Azure.ResourceManager.Models; - -[assembly: CodeGenSuppressType("ManagedServiceIdentity")] -namespace Azure.ResourceManager.Models -{ - [JsonConverter(typeof(ManagedServiceIdentityConverter))] - public partial class ManagedServiceIdentity : IJsonModel - { - internal void Write(Utf8JsonWriter writer, ModelReaderWriterOptions options, JsonSerializerOptions jOptions = null) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagedServiceIdentity)} does not support '{format}' format."); - } - - writer.WriteStartObject(); - JsonSerializer.Serialize(writer, ManagedServiceIdentityType, jOptions); - if (options.Format != "W" && Optional.IsDefined(PrincipalId)) - { - writer.WritePropertyName("principalId"u8); - writer.WriteStringValue(PrincipalId.Value); - } - if (options.Format != "W" && Optional.IsDefined(TenantId)) - { - writer.WritePropertyName("tenantId"u8); - writer.WriteStringValue(TenantId.Value); - } - if (Optional.IsCollectionDefined(UserAssignedIdentities)) - { - writer.WritePropertyName("userAssignedIdentities"u8); - writer.WriteStartObject(); - foreach (var item in UserAssignedIdentities) - { - writer.WritePropertyName(item.Key); - JsonSerializer.Serialize(writer, item.Value, jOptions); - } - writer.WriteEndObject(); - } - writer.WriteEndObject(); - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - Write(writer, options, null); - } - - ManagedServiceIdentity IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagedServiceIdentity)} does not support '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagedServiceIdentity(document.RootElement, options); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagedServiceIdentity)} does not support '{options.Format}' format."); - } - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ManagedServiceIdentityType), out propertyOverride); - if (Optional.IsDefined(ManagedServiceIdentityType) || hasPropertyOverride) - { - builder.Append(" type:"); - if (hasPropertyOverride) - { - builder.AppendLine($" {propertyOverride}"); - } - else - { - builder.AppendLine($" '{ManagedServiceIdentityType}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(UserAssignedIdentities), out propertyOverride); - if (UserAssignedIdentities.Any() || hasPropertyOverride) - { - builder.Append(" userAssignedIdentities:"); - builder.AppendLine(" {"); - if (hasPropertyOverride) - { - builder.AppendLine($" {propertyOverride}"); - } - else - { - foreach (var item in UserAssignedIdentities) - { - builder.Append($" {item.Key}:"); - AppendChildObject(builder, item.Value, options, 4, false); - } - } - - builder.AppendLine(" }"); - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - private void AppendChildObject(StringBuilder stringBuilder, object childObject, ModelReaderWriterOptions options, int spaces, bool indentFirstLine) - { - string indent = new string(' ', spaces); - BinaryData data = ModelReaderWriter.Write(childObject, options, AzureResourceManagerContext.Default); - string[] lines = data.ToString().Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); - bool inMultilineString = false; - for (int i = 0; i < lines.Length; i++) - { - string line = lines[i]; - if (inMultilineString) - { - if (line.Contains("'''")) - { - inMultilineString = false; - } - stringBuilder.AppendLine(line); - continue; - } - if (line.Contains("'''")) - { - inMultilineString = true; - stringBuilder.AppendLine($"{indent}{line}"); - continue; - } - if (i == 0 && !indentFirstLine) - { - stringBuilder.AppendLine($" {line}"); - } - else - { - stringBuilder.AppendLine($"{indent}{line}"); - } - } - } - - internal static ManagedServiceIdentity DeserializeManagedServiceIdentity(JsonElement element, ModelReaderWriterOptions options, JsonSerializerOptions jOptions) - { - options ??= new ModelReaderWriterOptions("W"); - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - Guid? principalId = default; - Guid? tenantId = default; - ManagedServiceIdentityType type = default; - IDictionary userAssignedIdentities = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("principalId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null || property.Value.GetString().Length == 0) - { - continue; - } - principalId = property.Value.GetGuid(); - continue; - } - if (property.NameEquals("tenantId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null || property.Value.GetString().Length == 0) - { - continue; - } - tenantId = property.Value.GetGuid(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = JsonSerializer.Deserialize($"{{{property}}}"); - continue; - } - if (property.NameEquals("userAssignedIdentities"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(new ResourceIdentifier(property0.Name), JsonSerializer.Deserialize(property0.Value.GetRawText())); - } - userAssignedIdentities = dictionary; - continue; - } - } - return new ManagedServiceIdentity(principalId, tenantId, type, userAssignedIdentities ?? new ChangeTrackingDictionary()); - } - - internal static ManagedServiceIdentity DeserializeManagedServiceIdentity(JsonElement element, ModelReaderWriterOptions options = null) - { - return DeserializeManagedServiceIdentity(element, options, null); - } - - ManagedServiceIdentity IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeManagedServiceIdentity(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagedServiceIdentity)} does not support '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class ManagedServiceIdentityConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, ManagedServiceIdentity model, JsonSerializerOptions options) - { - model.Write(writer, new ModelReaderWriterOptions("W"), options); - } - public override ManagedServiceIdentity Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeManagedServiceIdentity(document.RootElement, null, options); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentity.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentity.cs deleted file mode 100644 index 96313186cf..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentity.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// Managed service identity (system assigned and/or user assigned identities). - [PropertyReferenceType(new string[] { "UserAssignedIdentities" })] - public partial class ManagedServiceIdentity - { - /// Initializes a new instance of ManagedServiceIdentity. - /// Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). - [InitializationConstructor] - public ManagedServiceIdentity(ManagedServiceIdentityType managedServiceIdentityType) - { - ManagedServiceIdentityType = managedServiceIdentityType; - UserAssignedIdentities = new ChangeTrackingDictionary(); - } - - /// Initializes a new instance of ManagedServiceIdentity. - /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. - /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. - /// Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). - /// 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. - [SerializationConstructor] - internal ManagedServiceIdentity(Guid? principalId, Guid? tenantId, ManagedServiceIdentityType managedServiceIdentityType, IDictionary userAssignedIdentities) - { - PrincipalId = principalId; - TenantId = tenantId; - ManagedServiceIdentityType = managedServiceIdentityType; - UserAssignedIdentities = userAssignedIdentities; - } - - /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. - public Guid? PrincipalId { get; } - /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. - public Guid? TenantId { get; } - /// Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). - public ManagedServiceIdentityType ManagedServiceIdentityType { get; set; } - /// 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. - public IDictionary UserAssignedIdentities { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentityType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentityType.cs deleted file mode 100644 index 7954ef73df..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentityType.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace Azure.ResourceManager.Models -{ - /// Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). - [JsonConverter(typeof(ManagedServiceIdentityTypeConverter))] - public readonly partial struct ManagedServiceIdentityType : IEquatable - { - internal partial class ManagedServiceIdentityTypeConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, ManagedServiceIdentityType model, JsonSerializerOptions options) - { - writer.WritePropertyName("type"); - writer.WriteStringValue(model.ToString()); - } - public override ManagedServiceIdentityType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - foreach (var property in document.RootElement.EnumerateObject()) - { - if (property.Value.ValueKind == JsonValueKind.Null) - return default; - else - return new ManagedServiceIdentityType(property.Value.GetString()); - } - return null; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/SystemAssignedServiceIdentity.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/SystemAssignedServiceIdentity.cs deleted file mode 100644 index e887668292..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/SystemAssignedServiceIdentity.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ComponentModel; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// Managed service identity (either system assigned, or none). - // this class is consolidated into the ManagedServiceIdentity class. - [Obsolete("This type is obsolete and will be removed in a future release.", false)] - [EditorBrowsable(EditorBrowsableState.Never)] - public partial class SystemAssignedServiceIdentity - { - /// Initializes a new instance of SystemAssignedServiceIdentity. - /// Type of managed service identity (either system assigned, or none). - [InitializationConstructor] - public SystemAssignedServiceIdentity(SystemAssignedServiceIdentityType systemAssignedServiceIdentityType) - { - Identity = new ManagedServiceIdentity(systemAssignedServiceIdentityType.ToString()); - } - - /// Initializes a new instance of SystemAssignedServiceIdentity. - /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. - /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. - /// Type of managed service identity (either system assigned, or none). - [SerializationConstructor] - internal SystemAssignedServiceIdentity(Guid? principalId, Guid? tenantId, SystemAssignedServiceIdentityType systemAssignedServiceIdentityType) - { - Identity = new ManagedServiceIdentity(principalId, tenantId, systemAssignedServiceIdentityType.ToString(), null); - } - - /// Initializes a new instance of SystemAssignedServiceIdentity by given ManagedServiceIdentity. - internal SystemAssignedServiceIdentity(ManagedServiceIdentity managedServiceIdentity) - { - if (managedServiceIdentity == null) - { - throw new ArgumentNullException(); - } - Identity = managedServiceIdentity; - } - - internal ManagedServiceIdentity Identity { get; set; } - - /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. - public Guid? PrincipalId - { - get => Identity.PrincipalId; - } - /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. - public Guid? TenantId - { - get => Identity.TenantId; - } - /// Type of managed service identity (either system assigned, or none). - public SystemAssignedServiceIdentityType SystemAssignedServiceIdentityType - { - get => Identity.ManagedServiceIdentityType.ToString(); - set => Identity.ManagedServiceIdentityType = value.ToString(); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/SystemAssignedServiceIdentityType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/SystemAssignedServiceIdentityType.cs deleted file mode 100644 index 15fb71110a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/Models/SystemAssignedServiceIdentityType.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Models -{ - // this struct is consolidated into ManagedServiceIdentityType. - [Obsolete("This type is obsolete and will be removed in a future release.", false)] - [EditorBrowsable(EditorBrowsableState.Never)] - public readonly partial struct SystemAssignedServiceIdentityType - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/ResourceManagerModelFactory.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/ResourceManagerModelFactory.cs deleted file mode 100644 index c5d2b26469..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Custom/ResourceManagerModelFactory.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Models -{ - /// Model factory for read-only models. - public static partial class ResourceManagerModelFactory - { - /// Initializes a new instance of LocationExpanded. - /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. - /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. - /// Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). - /// 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. - /// A new instance for mocking. - public static ManagedServiceIdentity ManagedServiceIdentity(Guid? principalId = null, Guid? tenantId = null, ManagedServiceIdentityType managedServiceIdentityType = default, IDictionary userAssignedIdentities = null) - { - return new ManagedServiceIdentity(principalId, tenantId, managedServiceIdentityType, userAssignedIdentities); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/Argument.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/Argument.cs deleted file mode 100644 index 0e6dfdb59a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/Argument.cs +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; - -namespace Azure.ResourceManager -{ - internal static class Argument - { - public static void AssertNotNull(T value, string name) - { - if (value is null) - { - throw new ArgumentNullException(name); - } - } - - public static void AssertNotNull(T? value, string name) - where T : struct - { - if (!value.HasValue) - { - throw new ArgumentNullException(name); - } - } - - public static void AssertNotNullOrEmpty(IEnumerable value, string name) - { - if (value is null) - { - throw new ArgumentNullException(name); - } - if (value is ICollection collectionOfT && collectionOfT.Count == 0) - { - throw new ArgumentException("Value cannot be an empty collection.", name); - } - if (value is ICollection collection && collection.Count == 0) - { - throw new ArgumentException("Value cannot be an empty collection.", name); - } - using IEnumerator e = value.GetEnumerator(); - if (!e.MoveNext()) - { - throw new ArgumentException("Value cannot be an empty collection.", name); - } - } - - public static void AssertNotNullOrEmpty(string value, string name) - { - if (value is null) - { - throw new ArgumentNullException(name); - } - if (value.Length == 0) - { - throw new ArgumentException("Value cannot be an empty string.", name); - } - } - - public static void AssertNotNullOrWhiteSpace(string value, string name) - { - if (value is null) - { - throw new ArgumentNullException(name); - } - if (string.IsNullOrWhiteSpace(value)) - { - throw new ArgumentException("Value cannot be empty or contain only white-space characters.", name); - } - } - - public static void AssertNotDefault(ref T value, string name) - where T : struct, IEquatable - { - if (value.Equals(default)) - { - throw new ArgumentException("Value cannot be empty.", name); - } - } - - public static void AssertInRange(T value, T minimum, T maximum, string name) - where T : notnull, IComparable - { - if (minimum.CompareTo(value) > 0) - { - throw new ArgumentOutOfRangeException(name, "Value is less than the minimum allowed."); - } - if (maximum.CompareTo(value) < 0) - { - throw new ArgumentOutOfRangeException(name, "Value is greater than the maximum allowed."); - } - } - - public static void AssertEnumDefined(Type enumType, object value, string name) - { - if (!Enum.IsDefined(enumType, value)) - { - throw new ArgumentException($"Value not defined for {enumType.FullName}.", name); - } - } - - public static T CheckNotNull(T value, string name) - where T : class - { - AssertNotNull(value, name); - return value; - } - - public static string CheckNotNullOrEmpty(string value, string name) - { - AssertNotNullOrEmpty(value, name); - return value; - } - - public static void AssertNull(T value, string name, string message = null) - { - if (value != null) - { - throw new ArgumentException(message ?? "Value must be null.", name); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/BicepSerializationHelpers.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/BicepSerializationHelpers.cs deleted file mode 100644 index 633bf5b166..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/BicepSerializationHelpers.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text; - -namespace Azure.ResourceManager -{ - internal static class BicepSerializationHelpers - { - public static void AppendChildObject(StringBuilder stringBuilder, object childObject, ModelReaderWriterOptions options, int spaces, bool indentFirstLine, string formattedPropertyName) - { - string indent = new string(' ', spaces); - int emptyObjectLength = 2 + spaces + Environment.NewLine.Length + Environment.NewLine.Length; - int length = stringBuilder.Length; - bool inMultilineString = false; - - BinaryData data = ModelReaderWriter.Write(childObject, options, AzureResourceManagerContext.Default); - string[] lines = data.ToString().Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); - for (int i = 0; i < lines.Length; i++) - { - string line = lines[i]; - if (inMultilineString) - { - if (line.Contains("'''")) - { - inMultilineString = false; - } - stringBuilder.AppendLine(line); - continue; - } - if (line.Contains("'''")) - { - inMultilineString = true; - stringBuilder.AppendLine($"{indent}{line}"); - continue; - } - if (i == 0 && !indentFirstLine) - { - stringBuilder.AppendLine($"{line}"); - } - else - { - stringBuilder.AppendLine($"{indent}{line}"); - } - } - if (stringBuilder.Length == length + emptyObjectLength) - { - stringBuilder.Length = stringBuilder.Length - emptyObjectLength - formattedPropertyName.Length; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/ChangeTrackingDictionary.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/ChangeTrackingDictionary.cs deleted file mode 100644 index 3e0457dd83..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/ChangeTrackingDictionary.cs +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; - -namespace Azure.ResourceManager -{ - internal class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary where TKey : notnull - { - private IDictionary _innerDictionary; - - public ChangeTrackingDictionary() - { - } - - public ChangeTrackingDictionary(IDictionary dictionary) - { - if (dictionary == null) - { - return; - } - _innerDictionary = new Dictionary(dictionary); - } - - public ChangeTrackingDictionary(IReadOnlyDictionary dictionary) - { - if (dictionary == null) - { - return; - } - _innerDictionary = new Dictionary(); - foreach (var pair in dictionary) - { - _innerDictionary.Add(pair); - } - } - - public bool IsUndefined => _innerDictionary == null; - - public int Count => IsUndefined ? 0 : EnsureDictionary().Count; - - public bool IsReadOnly => IsUndefined ? false : EnsureDictionary().IsReadOnly; - - public ICollection Keys => IsUndefined ? Array.Empty() : EnsureDictionary().Keys; - - public ICollection Values => IsUndefined ? Array.Empty() : EnsureDictionary().Values; - - public TValue this[TKey key] - { - get - { - if (IsUndefined) - { - throw new KeyNotFoundException(nameof(key)); - } - return EnsureDictionary()[key]; - } - set - { - EnsureDictionary()[key] = value; - } - } - - IEnumerable IReadOnlyDictionary.Keys => Keys; - - IEnumerable IReadOnlyDictionary.Values => Values; - - public IEnumerator> GetEnumerator() - { - if (IsUndefined) - { - IEnumerator> enumerateEmpty() - { - yield break; - } - return enumerateEmpty(); - } - return EnsureDictionary().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - public void Add(KeyValuePair item) - { - EnsureDictionary().Add(item); - } - - public void Clear() - { - EnsureDictionary().Clear(); - } - - public bool Contains(KeyValuePair item) - { - if (IsUndefined) - { - return false; - } - return EnsureDictionary().Contains(item); - } - - public void CopyTo(KeyValuePair[] array, int index) - { - if (IsUndefined) - { - return; - } - EnsureDictionary().CopyTo(array, index); - } - - public bool Remove(KeyValuePair item) - { - if (IsUndefined) - { - return false; - } - return EnsureDictionary().Remove(item); - } - - public void Add(TKey key, TValue value) - { - EnsureDictionary().Add(key, value); - } - - public bool ContainsKey(TKey key) - { - if (IsUndefined) - { - return false; - } - return EnsureDictionary().ContainsKey(key); - } - - public bool Remove(TKey key) - { - if (IsUndefined) - { - return false; - } - return EnsureDictionary().Remove(key); - } - - public bool TryGetValue(TKey key, out TValue value) - { - if (IsUndefined) - { - value = default; - return false; - } - return EnsureDictionary().TryGetValue(key, out value); - } - - public IDictionary EnsureDictionary() - { - return _innerDictionary ??= new Dictionary(); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/ChangeTrackingList.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/ChangeTrackingList.cs deleted file mode 100644 index 1837046c52..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/ChangeTrackingList.cs +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; - -namespace Azure.ResourceManager -{ - internal class ChangeTrackingList : IList, IReadOnlyList - { - private IList _innerList; - - public ChangeTrackingList() - { - } - - public ChangeTrackingList(IList innerList) - { - if (innerList != null) - { - _innerList = innerList; - } - } - - public ChangeTrackingList(IReadOnlyList innerList) - { - if (innerList != null) - { - _innerList = innerList.ToList(); - } - } - - public bool IsUndefined => _innerList == null; - - public int Count => IsUndefined ? 0 : EnsureList().Count; - - public bool IsReadOnly => IsUndefined ? false : EnsureList().IsReadOnly; - - public T this[int index] - { - get - { - if (IsUndefined) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - return EnsureList()[index]; - } - set - { - if (IsUndefined) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - EnsureList()[index] = value; - } - } - - public void Reset() - { - _innerList = null; - } - - public IEnumerator GetEnumerator() - { - if (IsUndefined) - { - IEnumerator enumerateEmpty() - { - yield break; - } - return enumerateEmpty(); - } - return EnsureList().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - public void Add(T item) - { - EnsureList().Add(item); - } - - public void Clear() - { - EnsureList().Clear(); - } - - public bool Contains(T item) - { - if (IsUndefined) - { - return false; - } - return EnsureList().Contains(item); - } - - public void CopyTo(T[] array, int arrayIndex) - { - if (IsUndefined) - { - return; - } - EnsureList().CopyTo(array, arrayIndex); - } - - public bool Remove(T item) - { - if (IsUndefined) - { - return false; - } - return EnsureList().Remove(item); - } - - public int IndexOf(T item) - { - if (IsUndefined) - { - return -1; - } - return EnsureList().IndexOf(item); - } - - public void Insert(int index, T item) - { - EnsureList().Insert(index, item); - } - - public void RemoveAt(int index) - { - if (IsUndefined) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - EnsureList().RemoveAt(index); - } - - public IList EnsureList() - { - return _innerList ??= new List(); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/ModelSerializationExtensions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/ModelSerializationExtensions.cs deleted file mode 100644 index c879f184e7..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/ModelSerializationExtensions.cs +++ /dev/null @@ -1,407 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.Text.Json; -using System.Xml; -using Azure.Core; - -namespace Azure.ResourceManager -{ - internal static class ModelSerializationExtensions - { - internal static readonly JsonDocumentOptions JsonDocumentOptions = new JsonDocumentOptions { MaxDepth = 256 }; - internal static readonly ModelReaderWriterOptions WireOptions = new ModelReaderWriterOptions("W"); - internal static readonly BinaryData SentinelValue = BinaryData.FromBytes("\"__EMPTY__\""u8.ToArray()); - - public static object GetObject(this JsonElement element) - { - switch (element.ValueKind) - { - case JsonValueKind.String: - return element.GetString(); - case JsonValueKind.Number: - if (element.TryGetInt32(out int intValue)) - { - return intValue; - } - if (element.TryGetInt64(out long longValue)) - { - return longValue; - } - return element.GetDouble(); - case JsonValueKind.True: - return true; - case JsonValueKind.False: - return false; - case JsonValueKind.Undefined: - case JsonValueKind.Null: - return null; - case JsonValueKind.Object: - var dictionary = new Dictionary(); - foreach (var jsonProperty in element.EnumerateObject()) - { - dictionary.Add(jsonProperty.Name, jsonProperty.Value.GetObject()); - } - return dictionary; - case JsonValueKind.Array: - var list = new List(); - foreach (var item in element.EnumerateArray()) - { - list.Add(item.GetObject()); - } - return list.ToArray(); - default: - throw new NotSupportedException($"Not supported value kind {element.ValueKind}"); - } - } - - public static byte[] GetBytesFromBase64(this JsonElement element, string format) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - - return format switch - { - "U" => TypeFormatters.FromBase64UrlString(element.GetRequiredString()), - "D" => element.GetBytesFromBase64(), - _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) - }; - } - - public static DateTimeOffset GetDateTimeOffset(this JsonElement element, string format) => format switch - { - "U" when element.ValueKind == JsonValueKind.Number => DateTimeOffset.FromUnixTimeSeconds(element.GetInt64()), - _ => TypeFormatters.ParseDateTimeOffset(element.GetString(), format) - }; - - public static TimeSpan GetTimeSpan(this JsonElement element, string format) => TypeFormatters.ParseTimeSpan(element.GetString(), format); - - public static char GetChar(this JsonElement element) - { - if (element.ValueKind == JsonValueKind.String) - { - var text = element.GetString(); - if (text == null || text.Length != 1) - { - throw new NotSupportedException($"Cannot convert \"{text}\" to a char"); - } - return text[0]; - } - else - { - throw new NotSupportedException($"Cannot convert {element.ValueKind} to a char"); - } - } - - [Conditional("DEBUG")] - public static void ThrowNonNullablePropertyIsNull(this JsonProperty property) - { - throw new JsonException($"A property '{property.Name}' defined as non-nullable but received as null from the service. This exception only happens in DEBUG builds of the library and would be ignored in the release build"); - } - - public static string GetRequiredString(this JsonElement element) - { - var value = element.GetString(); - if (value == null) - { - throw new InvalidOperationException($"The requested operation requires an element of type 'String', but the target element has type '{element.ValueKind}'."); - } - return value; - } - - public static void WriteStringValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) - { - writer.WriteStringValue(TypeFormatters.ToString(value, format)); - } - - public static void WriteStringValue(this Utf8JsonWriter writer, DateTime value, string format) - { - writer.WriteStringValue(TypeFormatters.ToString(value, format)); - } - - public static void WriteStringValue(this Utf8JsonWriter writer, TimeSpan value, string format) - { - writer.WriteStringValue(TypeFormatters.ToString(value, format)); - } - - public static void WriteStringValue(this Utf8JsonWriter writer, char value) - { - writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture)); - } - - public static void WriteBase64StringValue(this Utf8JsonWriter writer, byte[] value, string format) - { - if (value == null) - { - writer.WriteNullValue(); - return; - } - switch (format) - { - case "U": - writer.WriteStringValue(TypeFormatters.ToBase64UrlString(value)); - break; - case "D": - writer.WriteBase64StringValue(value); - break; - default: - throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)); - } - } - - public static void WriteNumberValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) - { - if (format != "U") - { - throw new ArgumentOutOfRangeException(nameof(format), "Only 'U' format is supported when writing a DateTimeOffset as a Number."); - } - writer.WriteNumberValue(value.ToUnixTimeSeconds()); - } - - public static void WriteObjectValue(this Utf8JsonWriter writer, T value, ModelReaderWriterOptions options = null) - { - switch (value) - { - case null: - writer.WriteNullValue(); - break; - case IJsonModel jsonModel: - jsonModel.Write(writer, options ?? WireOptions); - break; - case IUtf8JsonSerializable serializable: - serializable.Write(writer); - break; - case byte[] bytes: - writer.WriteBase64StringValue(bytes); - break; - case BinaryData bytes0: - writer.WriteBase64StringValue(bytes0); - break; - case JsonElement json: - json.WriteTo(writer); - break; - case int i: - writer.WriteNumberValue(i); - break; - case decimal d: - writer.WriteNumberValue(d); - break; - case double d0: - if (double.IsNaN(d0)) - { - writer.WriteStringValue("NaN"); - } - else - { - writer.WriteNumberValue(d0); - } - break; - case float f: - writer.WriteNumberValue(f); - break; - case long l: - writer.WriteNumberValue(l); - break; - case string s: - writer.WriteStringValue(s); - break; - case bool b: - writer.WriteBooleanValue(b); - break; - case Guid g: - writer.WriteStringValue(g); - break; - case DateTimeOffset dateTimeOffset: - writer.WriteStringValue(dateTimeOffset, "O"); - break; - case DateTime dateTime: - writer.WriteStringValue(dateTime, "O"); - break; - case IEnumerable> enumerable: - writer.WriteStartObject(); - foreach (var pair in enumerable) - { - writer.WritePropertyName(pair.Key); - writer.WriteObjectValue(pair.Value, options); - } - writer.WriteEndObject(); - break; - case IEnumerable objectEnumerable: - writer.WriteStartArray(); - foreach (var item in objectEnumerable) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - break; - case TimeSpan timeSpan: - writer.WriteStringValue(timeSpan, "P"); - break; - default: - throw new NotSupportedException($"Not supported type {value.GetType()}"); - } - } - - public static void WriteObjectValue(this Utf8JsonWriter writer, object value, ModelReaderWriterOptions options = null) - { - writer.WriteObjectValue(value, options); - } - - internal static bool IsSentinelValue(BinaryData value) - { - ReadOnlySpan sentinelSpan = SentinelValue.ToMemory().Span; - ReadOnlySpan valueSpan = value.ToMemory().Span; - return sentinelSpan.SequenceEqual(valueSpan); - } - - internal static class TypeFormatters - { - private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; - public const string DefaultNumberFormat = "G"; - - public static string ToString(bool value) => value ? "true" : "false"; - - public static string ToString(DateTime value, string format) => value.Kind switch - { - DateTimeKind.Utc => ToString((DateTimeOffset)value, format), - _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Azure SDK requires it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") - }; - - public static string ToString(DateTimeOffset value, string format) => format switch - { - "D" => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), - "U" => value.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), - "O" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), - "o" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), - "R" => value.ToString("r", CultureInfo.InvariantCulture), - _ => value.ToString(format, CultureInfo.InvariantCulture) - }; - - public static string ToString(TimeSpan value, string format) => format switch - { - "P" => XmlConvert.ToString(value), - _ => value.ToString(format, CultureInfo.InvariantCulture) - }; - - public static string ToString(byte[] value, string format) => format switch - { - "U" => ToBase64UrlString(value), - "D" => Convert.ToBase64String(value), - _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) - }; - - public static string ToBase64UrlString(byte[] value) - { - int numWholeOrPartialInputBlocks = checked(value.Length + 2) / 3; - int size = checked(numWholeOrPartialInputBlocks * 4); - char[] output = new char[size]; - - int numBase64Chars = Convert.ToBase64CharArray(value, 0, value.Length, output, 0); - - int i = 0; - for (; i < numBase64Chars; i++) - { - char ch = output[i]; - if (ch == '+') - { - output[i] = '-'; - } - else - { - if (ch == '/') - { - output[i] = '_'; - } - else - { - if (ch == '=') - { - break; - } - } - } - } - - return new string(output, 0, i); - } - - public static byte[] FromBase64UrlString(string value) - { - int paddingCharsToAdd = (value.Length % 4) switch - { - 0 => 0, - 2 => 2, - 3 => 1, - _ => throw new InvalidOperationException("Malformed input") - }; - char[] output = new char[(value.Length + paddingCharsToAdd)]; - int i = 0; - for (; i < value.Length; i++) - { - char ch = value[i]; - if (ch == '-') - { - output[i] = '+'; - } - else - { - if (ch == '_') - { - output[i] = '/'; - } - else - { - output[i] = ch; - } - } - } - - for (; i < output.Length; i++) - { - output[i] = '='; - } - - return Convert.FromBase64CharArray(output, 0, output.Length); - } - - public static DateTimeOffset ParseDateTimeOffset(string value, string format) => format switch - { - "U" => DateTimeOffset.FromUnixTimeSeconds(long.Parse(value, CultureInfo.InvariantCulture)), - _ => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) - }; - - public static TimeSpan ParseTimeSpan(string value, string format) => format switch - { - "P" => XmlConvert.ToTimeSpan(value), - _ => TimeSpan.ParseExact(value, format, CultureInfo.InvariantCulture) - }; - - public static string ConvertToString(object value, string format = null) => value switch - { - null => "null", - string s => s, - bool b => ToString(b), - int or float or double or long or decimal => ((IFormattable)value).ToString(DefaultNumberFormat, CultureInfo.InvariantCulture), - byte[] b0 when format != null => ToString(b0, format), - IEnumerable s0 => string.Join(",", s0), - DateTimeOffset dateTime when format != null => ToString(dateTime, format), - TimeSpan timeSpan when format != null => ToString(timeSpan, format), - TimeSpan timeSpan0 => XmlConvert.ToString(timeSpan0), - Guid guid => guid.ToString(), - BinaryData binaryData => ConvertToString(binaryData.ToArray(), format), - _ => value.ToString() - }; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/Optional.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/Optional.cs deleted file mode 100644 index c21cb37eee..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/Optional.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.ResourceManager -{ - internal static class Optional - { - public static bool IsCollectionDefined(IEnumerable collection) - { - return !(collection is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined); - } - - public static bool IsCollectionDefined(IDictionary collection) - { - return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); - } - - public static bool IsCollectionDefined(IReadOnlyDictionary collection) - { - return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); - } - - public static bool IsDefined(T? value) - where T : struct - { - return value.HasValue; - } - - public static bool IsDefined(object value) - { - return value != null; - } - - public static bool IsDefined(JsonElement value) - { - return value.ValueKind != JsonValueKind.Undefined; - } - - public static bool IsDefined(string value) - { - return value != null; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/WirePathAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/WirePathAttribute.cs deleted file mode 100644 index 6a974d2a89..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Internal/WirePathAttribute.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager -{ - [AttributeUsage(AttributeTargets.Property)] - internal class WirePathAttribute : Attribute - { - private string _wirePath; - - public WirePathAttribute(string wirePath) - { - _wirePath = wirePath; - } - - public override string ToString() - { - return _wirePath; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmPlan.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmPlan.Serialization.cs deleted file mode 100644 index 95e2fd6d05..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmPlan.Serialization.cs +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - [JsonConverter(typeof(ArmPlanConverter))] - public partial class ArmPlan : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - private void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmPlan)} does not support writing '{format}' format."); - } - - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - writer.WritePropertyName("publisher"u8); - writer.WriteStringValue(Publisher); - writer.WritePropertyName("product"u8); - writer.WriteStringValue(Product); - if (Optional.IsDefined(PromotionCode)) - { - writer.WritePropertyName("promotionCode"u8); - writer.WriteStringValue(PromotionCode); - } - if (Optional.IsDefined(Version)) - { - writer.WritePropertyName("version"u8); - writer.WriteStringValue(Version); - } - } - - ArmPlan IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmPlan)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeArmPlan(document.RootElement, options); - } - - internal static ArmPlan DeserializeArmPlan(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - string publisher = default; - string product = default; - string promotionCode = default; - string version = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("publisher"u8)) - { - publisher = property.Value.GetString(); - continue; - } - if (property.NameEquals("product"u8)) - { - product = property.Value.GetString(); - continue; - } - if (property.NameEquals("promotionCode"u8)) - { - promotionCode = property.Value.GetString(); - continue; - } - if (property.NameEquals("version"u8)) - { - version = property.Value.GetString(); - continue; - } - } - return new ArmPlan(name, publisher, product, promotionCode, version); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Publisher), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" publisher: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Publisher)) - { - builder.Append(" publisher: "); - if (Publisher.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Publisher}'''"); - } - else - { - builder.AppendLine($"'{Publisher}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Product), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" product: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Product)) - { - builder.Append(" product: "); - if (Product.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Product}'''"); - } - else - { - builder.AppendLine($"'{Product}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PromotionCode), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" promotionCode: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PromotionCode)) - { - builder.Append(" promotionCode: "); - if (PromotionCode.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{PromotionCode}'''"); - } - else - { - builder.AppendLine($"'{PromotionCode}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Version), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" version: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Version)) - { - builder.Append(" version: "); - if (Version.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Version}'''"); - } - else - { - builder.AppendLine($"'{Version}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ArmPlan)} does not support writing '{options.Format}' format."); - } - } - - ArmPlan IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeArmPlan(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ArmPlan)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class ArmPlanConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, ArmPlan model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model, ModelSerializationExtensions.WireOptions); - } - - public override ArmPlan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeArmPlan(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmPlan.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmPlan.cs deleted file mode 100644 index 711ac5f348..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmPlan.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// Plan for the resource. - [PropertyReferenceType] - public partial class ArmPlan - { - /// Initializes a new instance of . - /// A user defined name of the 3rd Party Artifact that is being procured. - /// The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic. - /// The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to the OfferID specified for the artifact at the time of Data Market onboarding. - /// , or is null. - [InitializationConstructor] - public ArmPlan(string name, string publisher, string product) - { - Argument.AssertNotNull(name, nameof(name)); - Argument.AssertNotNull(publisher, nameof(publisher)); - Argument.AssertNotNull(product, nameof(product)); - - Name = name; - Publisher = publisher; - Product = product; - } - - /// Initializes a new instance of . - /// A user defined name of the 3rd Party Artifact that is being procured. - /// The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic. - /// The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to the OfferID specified for the artifact at the time of Data Market onboarding. - /// A publisher provided promotion code as provisioned in Data Market for the said product/artifact. - /// The version of the desired product/artifact. - [SerializationConstructor] - internal ArmPlan(string name, string publisher, string product, string promotionCode, string version) - { - Name = name; - Publisher = publisher; - Product = product; - PromotionCode = promotionCode; - Version = version; - } - - /// Initializes a new instance of for deserialization. - internal ArmPlan() - { - } - - /// A user defined name of the 3rd Party Artifact that is being procured. - [WirePath("name")] - public string Name { get; set; } - /// The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic. - [WirePath("publisher")] - public string Publisher { get; set; } - /// The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to the OfferID specified for the artifact at the time of Data Market onboarding. - [WirePath("product")] - public string Product { get; set; } - /// A publisher provided promotion code as provisioned in Data Market for the said product/artifact. - [WirePath("promotionCode")] - public string PromotionCode { get; set; } - /// The version of the desired product/artifact. - [WirePath("version")] - public string Version { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmSku.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmSku.Serialization.cs deleted file mode 100644 index ee12d1ffab..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmSku.Serialization.cs +++ /dev/null @@ -1,289 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - [JsonConverter(typeof(ArmSkuConverter))] - public partial class ArmSku : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - private void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmSku)} does not support writing '{format}' format."); - } - - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - if (Optional.IsDefined(Tier)) - { - writer.WritePropertyName("tier"u8); - writer.WriteStringValue(Tier.Value.ToSerialString()); - } - if (Optional.IsDefined(Size)) - { - writer.WritePropertyName("size"u8); - writer.WriteStringValue(Size); - } - if (Optional.IsDefined(Family)) - { - writer.WritePropertyName("family"u8); - writer.WriteStringValue(Family); - } - if (Optional.IsDefined(Capacity)) - { - writer.WritePropertyName("capacity"u8); - writer.WriteNumberValue(Capacity.Value); - } - } - - ArmSku IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmSku)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeArmSku(document.RootElement, options); - } - - internal static ArmSku DeserializeArmSku(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - ArmSkuTier? tier = default; - string size = default; - string family = default; - int? capacity = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("tier"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - tier = property.Value.GetString().ToArmSkuTier(); - continue; - } - if (property.NameEquals("size"u8)) - { - size = property.Value.GetString(); - continue; - } - if (property.NameEquals("family"u8)) - { - family = property.Value.GetString(); - continue; - } - if (property.NameEquals("capacity"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - capacity = property.Value.GetInt32(); - continue; - } - } - return new ArmSku(name, tier, size, family, capacity); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Tier), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tier: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Tier)) - { - builder.Append(" tier: "); - builder.AppendLine($"'{Tier.Value.ToSerialString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Size), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" size: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Size)) - { - builder.Append(" size: "); - if (Size.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Size}'''"); - } - else - { - builder.AppendLine($"'{Size}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Family), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" family: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Family)) - { - builder.Append(" family: "); - if (Family.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Family}'''"); - } - else - { - builder.AppendLine($"'{Family}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Capacity), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" capacity: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Capacity)) - { - builder.Append(" capacity: "); - builder.AppendLine($"{Capacity.Value}"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ArmSku)} does not support writing '{options.Format}' format."); - } - } - - ArmSku IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeArmSku(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ArmSku)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class ArmSkuConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, ArmSku model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model, ModelSerializationExtensions.WireOptions); - } - - public override ArmSku Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeArmSku(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmSku.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmSku.cs deleted file mode 100644 index 4a4de3ba03..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmSku.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// The resource model definition representing SKU. - [PropertyReferenceType] - public partial class ArmSku - { - /// Initializes a new instance of . - /// The name of the SKU. Ex - P3. It is typically a letter+number code. - /// is null. - [InitializationConstructor] - public ArmSku(string name) - { - Argument.AssertNotNull(name, nameof(name)); - - Name = name; - } - - /// Initializes a new instance of . - /// The name of the SKU. Ex - P3. It is typically a letter+number code. - /// This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required on a PUT. - /// The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. - /// If the service has different generations of hardware, for the same SKU, then that can be captured here. - /// If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the resource this may be omitted. - [SerializationConstructor] - internal ArmSku(string name, ArmSkuTier? tier, string size, string family, int? capacity) - { - Name = name; - Tier = tier; - Size = size; - Family = family; - Capacity = capacity; - } - - /// Initializes a new instance of for deserialization. - internal ArmSku() - { - } - - /// The name of the SKU. Ex - P3. It is typically a letter+number code. - [WirePath("name")] - public string Name { get; set; } - /// This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required on a PUT. - [WirePath("tier")] - public ArmSkuTier? Tier { get; set; } - /// The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. - [WirePath("size")] - public string Size { get; set; } - /// If the service has different generations of hardware, for the same SKU, then that can be captured here. - [WirePath("family")] - public string Family { get; set; } - /// If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the resource this may be omitted. - [WirePath("capacity")] - public int? Capacity { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmSkuTier.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmSkuTier.Serialization.cs deleted file mode 100644 index c640e16a48..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmSkuTier.Serialization.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.Models -{ - internal static partial class ArmSkuTierExtensions - { - public static string ToSerialString(this ArmSkuTier value) => value switch - { - ArmSkuTier.Free => "Free", - ArmSkuTier.Basic => "Basic", - ArmSkuTier.Standard => "Standard", - ArmSkuTier.Premium => "Premium", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ArmSkuTier value.") - }; - - public static ArmSkuTier ToArmSkuTier(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Free")) return ArmSkuTier.Free; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Basic")) return ArmSkuTier.Basic; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Standard")) return ArmSkuTier.Standard; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Premium")) return ArmSkuTier.Premium; - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ArmSkuTier value."); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmSkuTier.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmSkuTier.cs deleted file mode 100644 index 4320a2d3b4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ArmSkuTier.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.Models -{ - /// This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required on a PUT. - public enum ArmSkuTier - { - /// Free. - Free, - /// Basic. - Basic, - /// Standard. - Standard, - /// Premium. - Premium - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/AzureResourceManagerContext.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/AzureResourceManagerContext.cs deleted file mode 100644 index f26fee2f3a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/AzureResourceManagerContext.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.ClientModel.Primitives; - -namespace Azure.ResourceManager -{ - /// - /// Context class which will be filled in by the System.ClientModel.SourceGeneration. - /// For more information see 'https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/System.ClientModel/src/docs/ModelReaderWriterContext.md' - /// - public partial class AzureResourceManagerContext : ModelReaderWriterContext - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/CreatedByType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/CreatedByType.cs deleted file mode 100644 index f7a4c34f58..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/CreatedByType.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Models -{ - /// The type of identity that created the resource. - public readonly partial struct CreatedByType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public CreatedByType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string UserValue = "User"; - private const string ApplicationValue = "Application"; - private const string ManagedIdentityValue = "ManagedIdentity"; - private const string KeyValue = "Key"; - - /// User. - public static CreatedByType User { get; } = new CreatedByType(UserValue); - /// Application. - public static CreatedByType Application { get; } = new CreatedByType(ApplicationValue); - /// ManagedIdentity. - public static CreatedByType ManagedIdentity { get; } = new CreatedByType(ManagedIdentityValue); - /// Key. - public static CreatedByType Key { get; } = new CreatedByType(KeyValue); - /// Determines if two values are the same. - public static bool operator ==(CreatedByType left, CreatedByType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(CreatedByType left, CreatedByType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator CreatedByType(string value) => new CreatedByType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is CreatedByType other && Equals(other); - /// - public bool Equals(CreatedByType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/EncryptionProperties.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/EncryptionProperties.Serialization.cs deleted file mode 100644 index bc9ff0979a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/EncryptionProperties.Serialization.cs +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - [JsonConverter(typeof(EncryptionPropertiesConverter))] - public partial class EncryptionProperties : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(EncryptionProperties)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Status)) - { - writer.WritePropertyName("status"u8); - writer.WriteStringValue(Status.Value.ToString()); - } - if (Optional.IsDefined(KeyVaultProperties)) - { - writer.WritePropertyName("keyVaultProperties"u8); - writer.WriteObjectValue(KeyVaultProperties, options); - } - } - - EncryptionProperties IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(EncryptionProperties)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeEncryptionProperties(document.RootElement, options); - } - - internal static EncryptionProperties DeserializeEncryptionProperties(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - EncryptionStatus? status = default; - KeyVaultProperties keyVaultProperties = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("status"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - status = new EncryptionStatus(property.Value.GetString()); - continue; - } - if (property.NameEquals("keyVaultProperties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - keyVaultProperties = KeyVaultProperties.DeserializeKeyVaultProperties(property.Value, options); - continue; - } - } - return new EncryptionProperties(status, keyVaultProperties); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Status), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" status: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Status)) - { - builder.Append(" status: "); - builder.AppendLine($"'{Status.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(KeyVaultProperties), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" keyVaultProperties: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(KeyVaultProperties)) - { - builder.Append(" keyVaultProperties: "); - BicepSerializationHelpers.AppendChildObject(builder, KeyVaultProperties, options, 2, false, " keyVaultProperties: "); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(EncryptionProperties)} does not support writing '{options.Format}' format."); - } - } - - EncryptionProperties IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeEncryptionProperties(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(EncryptionProperties)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class EncryptionPropertiesConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, EncryptionProperties model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model, ModelSerializationExtensions.WireOptions); - } - - public override EncryptionProperties Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeEncryptionProperties(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/EncryptionProperties.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/EncryptionProperties.cs deleted file mode 100644 index 5b441bcc81..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/EncryptionProperties.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// Configuration of key for data encryption. - [PropertyReferenceType] - public partial class EncryptionProperties - { - /// Initializes a new instance of . - [InitializationConstructor] - public EncryptionProperties() - { - } - - /// Initializes a new instance of . - /// Indicates whether or not the encryption is enabled for container registry. - /// Key vault properties. - [SerializationConstructor] - internal EncryptionProperties(EncryptionStatus? status, KeyVaultProperties keyVaultProperties) - { - Status = status; - KeyVaultProperties = keyVaultProperties; - } - - /// Indicates whether or not the encryption is enabled for container registry. - [WirePath("status")] - public EncryptionStatus? Status { get; set; } - /// Key vault properties. - [WirePath("keyVaultProperties")] - public KeyVaultProperties KeyVaultProperties { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/EncryptionStatus.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/EncryptionStatus.cs deleted file mode 100644 index c69242b97c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/EncryptionStatus.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Models -{ - /// Indicates whether or not the encryption is enabled for container registry. - public readonly partial struct EncryptionStatus : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public EncryptionStatus(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string EnabledValue = "enabled"; - private const string DisabledValue = "disabled"; - - /// enabled. - public static EncryptionStatus Enabled { get; } = new EncryptionStatus(EnabledValue); - /// disabled. - public static EncryptionStatus Disabled { get; } = new EncryptionStatus(DisabledValue); - /// Determines if two values are the same. - public static bool operator ==(EncryptionStatus left, EncryptionStatus right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(EncryptionStatus left, EncryptionStatus right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator EncryptionStatus(string value) => new EncryptionStatus(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is EncryptionStatus other && Equals(other); - /// - public bool Equals(EncryptionStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/KeyVaultProperties.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/KeyVaultProperties.Serialization.cs deleted file mode 100644 index 5280cd7b90..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/KeyVaultProperties.Serialization.cs +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - [JsonConverter(typeof(KeyVaultPropertiesConverter))] - public partial class KeyVaultProperties : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(KeyVaultProperties)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(KeyIdentifier)) - { - writer.WritePropertyName("keyIdentifier"u8); - writer.WriteStringValue(KeyIdentifier); - } - if (Optional.IsDefined(Identity)) - { - writer.WritePropertyName("identity"u8); - writer.WriteStringValue(Identity); - } - } - - KeyVaultProperties IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(KeyVaultProperties)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeKeyVaultProperties(document.RootElement, options); - } - - internal static KeyVaultProperties DeserializeKeyVaultProperties(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string keyIdentifier = default; - string identity = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("keyIdentifier"u8)) - { - keyIdentifier = property.Value.GetString(); - continue; - } - if (property.NameEquals("identity"u8)) - { - identity = property.Value.GetString(); - continue; - } - } - return new KeyVaultProperties(keyIdentifier, identity); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(KeyIdentifier), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" keyIdentifier: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(KeyIdentifier)) - { - builder.Append(" keyIdentifier: "); - if (KeyIdentifier.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{KeyIdentifier}'''"); - } - else - { - builder.AppendLine($"'{KeyIdentifier}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Identity), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" identity: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Identity)) - { - builder.Append(" identity: "); - if (Identity.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Identity}'''"); - } - else - { - builder.AppendLine($"'{Identity}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(KeyVaultProperties)} does not support writing '{options.Format}' format."); - } - } - - KeyVaultProperties IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeKeyVaultProperties(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(KeyVaultProperties)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class KeyVaultPropertiesConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, KeyVaultProperties model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model, ModelSerializationExtensions.WireOptions); - } - - public override KeyVaultProperties Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeKeyVaultProperties(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/KeyVaultProperties.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/KeyVaultProperties.cs deleted file mode 100644 index 2e92a30cff..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/KeyVaultProperties.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// The KeyVaultProperties. - [PropertyReferenceType] - public partial class KeyVaultProperties - { - /// Initializes a new instance of . - [InitializationConstructor] - public KeyVaultProperties() - { - } - - /// Initializes a new instance of . - /// Key vault uri to access the encryption key. - /// The client ID of the identity which will be used to access key vault. - [SerializationConstructor] - internal KeyVaultProperties(string keyIdentifier, string identity) - { - KeyIdentifier = keyIdentifier; - Identity = identity; - } - - /// Key vault uri to access the encryption key. - [WirePath("keyIdentifier")] - public string KeyIdentifier { get; set; } - /// The client ID of the identity which will be used to access key vault. - [WirePath("identity")] - public string Identity { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ManagedServiceIdentityType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ManagedServiceIdentityType.cs deleted file mode 100644 index 826953ce1c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ManagedServiceIdentityType.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Models -{ - /// Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). - public readonly partial struct ManagedServiceIdentityType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ManagedServiceIdentityType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string NoneValue = "None"; - private const string SystemAssignedValue = "SystemAssigned"; - private const string UserAssignedValue = "UserAssigned"; - private const string SystemAssignedUserAssignedValue = "SystemAssigned, UserAssigned"; - - /// None. - public static ManagedServiceIdentityType None { get; } = new ManagedServiceIdentityType(NoneValue); - /// SystemAssigned. - public static ManagedServiceIdentityType SystemAssigned { get; } = new ManagedServiceIdentityType(SystemAssignedValue); - /// UserAssigned. - public static ManagedServiceIdentityType UserAssigned { get; } = new ManagedServiceIdentityType(UserAssignedValue); - /// SystemAssigned, UserAssigned. - public static ManagedServiceIdentityType SystemAssignedUserAssigned { get; } = new ManagedServiceIdentityType(SystemAssignedUserAssignedValue); - /// Determines if two values are the same. - public static bool operator ==(ManagedServiceIdentityType left, ManagedServiceIdentityType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ManagedServiceIdentityType left, ManagedServiceIdentityType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ManagedServiceIdentityType(string value) => new ManagedServiceIdentityType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ManagedServiceIdentityType other && Equals(other); - /// - public bool Equals(ManagedServiceIdentityType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/OperationStatusResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/OperationStatusResult.Serialization.cs deleted file mode 100644 index b28ac42cb6..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/OperationStatusResult.Serialization.cs +++ /dev/null @@ -1,407 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - [JsonConverter(typeof(OperationStatusResultConverter))] - public partial class OperationStatusResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(OperationStatusResult)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (options.Format != "W") - { - writer.WritePropertyName("status"u8); - writer.WriteStringValue(Status); - } - if (options.Format != "W" && Optional.IsDefined(PercentComplete)) - { - writer.WritePropertyName("percentComplete"u8); - writer.WriteNumberValue(PercentComplete.Value); - } - if (options.Format != "W" && Optional.IsDefined(StartOn)) - { - writer.WritePropertyName("startTime"u8); - writer.WriteStringValue(StartOn.Value, "O"); - } - if (options.Format != "W" && Optional.IsDefined(EndOn)) - { - writer.WritePropertyName("endTime"u8); - writer.WriteStringValue(EndOn.Value, "O"); - } - if (options.Format != "W" && Optional.IsCollectionDefined(Operations)) - { - writer.WritePropertyName("operations"u8); - writer.WriteStartArray(); - foreach (var item in Operations) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(Error)) - { - writer.WritePropertyName("error"u8); - JsonSerializer.Serialize(writer, Error); - } - } - - OperationStatusResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(OperationStatusResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeOperationStatusResult(document.RootElement, options); - } - - internal static OperationStatusResult DeserializeOperationStatusResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string name = default; - string status = default; - float? percentComplete = default; - DateTimeOffset? startTime = default; - DateTimeOffset? endTime = default; - IReadOnlyList operations = default; - ResponseError error = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("status"u8)) - { - status = property.Value.GetString(); - continue; - } - if (property.NameEquals("percentComplete"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - percentComplete = property.Value.GetSingle(); - continue; - } - if (property.NameEquals("startTime"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - startTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("endTime"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - endTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("operations"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(JsonSerializer.Deserialize(item.GetRawText())); - } - operations = array; - continue; - } - if (property.NameEquals("error"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - error = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - } - return new OperationStatusResult( - id, - name, - status, - percentComplete, - startTime, - endTime, - operations ?? new ChangeTrackingList(), - error); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Status), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" status: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Status)) - { - builder.Append(" status: "); - if (Status.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Status}'''"); - } - else - { - builder.AppendLine($"'{Status}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PercentComplete), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" percentComplete: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PercentComplete)) - { - builder.Append(" percentComplete: "); - builder.AppendLine($"'{PercentComplete.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(StartOn), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" startTime: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(StartOn)) - { - builder.Append(" startTime: "); - var formattedDateTimeString = TypeFormatters.ToString(StartOn.Value, "o"); - builder.AppendLine($"'{formattedDateTimeString}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(EndOn), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" endTime: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(EndOn)) - { - builder.Append(" endTime: "); - var formattedDateTimeString = TypeFormatters.ToString(EndOn.Value, "o"); - builder.AppendLine($"'{formattedDateTimeString}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Operations), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" operations: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Operations)) - { - if (Operations.Any()) - { - builder.Append(" operations: "); - builder.AppendLine("["); - foreach (var item in Operations) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " operations: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Error), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" error: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Error)) - { - builder.Append(" error: "); - BicepSerializationHelpers.AppendChildObject(builder, Error, options, 2, false, " error: "); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(OperationStatusResult)} does not support writing '{options.Format}' format."); - } - } - - OperationStatusResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeOperationStatusResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(OperationStatusResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class OperationStatusResultConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, OperationStatusResult model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model, ModelSerializationExtensions.WireOptions); - } - - public override OperationStatusResult Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeOperationStatusResult(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/OperationStatusResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/OperationStatusResult.cs deleted file mode 100644 index 5a902c73e8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/OperationStatusResult.cs +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// The current status of an async operation. - [TypeReferenceType] - public partial class OperationStatusResult - { - /// Initializes a new instance of . - /// Operation status. - [InitializationConstructor] - public OperationStatusResult(string status) - { - Status = status; - Operations = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// Fully qualified ID for the async operation. - /// Name of the async operation. - /// Operation status. - /// Percent of the operation that is complete. - /// The start time of the operation. - /// The end time of the operation. - /// The operations list. - /// If present, details of the operation error. - [SerializationConstructor] - protected OperationStatusResult(ResourceIdentifier id, string name, string status, float? percentComplete, DateTimeOffset? startOn, DateTimeOffset? endOn, IReadOnlyList operations, ResponseError error) - { - Id = id; - Name = name; - Status = status; - PercentComplete = percentComplete; - StartOn = startOn; - EndOn = endOn; - Operations = operations; - Error = error; - } - - /// Initializes a new instance of for deserialization. - protected OperationStatusResult() - { - } - - /// Fully qualified ID for the async operation. - [WirePath("id")] - public ResourceIdentifier Id { get; } - /// Name of the async operation. - [WirePath("name")] - public string Name { get; } - /// Operation status. - [WirePath("status")] - public string Status { get; } - /// Percent of the operation that is complete. - [WirePath("percentComplete")] - public float? PercentComplete { get; } - /// The start time of the operation. - [WirePath("startTime")] - public DateTimeOffset? StartOn { get; } - /// The end time of the operation. - [WirePath("endTime")] - public DateTimeOffset? EndOn { get; } - /// The operations list. - [WirePath("operations")] - public IReadOnlyList Operations { get; } - /// If present, details of the operation error. - [WirePath("error")] - public ResponseError Error { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ResourceData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ResourceData.Serialization.cs deleted file mode 100644 index 1b659410bc..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ResourceData.Serialization.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Models -{ - public partial class ResourceData - { - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (options.Format != "W") - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ResourceType); - } - if (options.Format != "W" && Optional.IsDefined(SystemData)) - { - writer.WritePropertyName("systemData"u8); - writer.WriteObjectValue(SystemData, options); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ResourceData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ResourceData.cs deleted file mode 100644 index 841b931f44..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/ResourceData.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// Common fields that are returned in the response for all Azure Resource Manager resources. - [ReferenceType(new string[] { "SystemData" })] - public abstract partial class ResourceData - { - /// Initializes a new instance of . - [InitializationConstructor] - protected ResourceData() - { - } - - /// Initializes a new instance of . - /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - /// The name of the resource. - /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". - /// Azure Resource Manager metadata containing createdBy and modifiedBy information. - [SerializationConstructor] - protected ResourceData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData) - { - Id = id; - Name = name; - ResourceType = resourceType; - SystemData = systemData; - } - - /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - public ResourceIdentifier Id { get; } - /// The name of the resource. - public string Name { get; } - /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". - public ResourceType ResourceType { get; } - /// Azure Resource Manager metadata containing createdBy and modifiedBy information. - public SystemData SystemData { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentity.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentity.Serialization.cs deleted file mode 100644 index 2e420c90b8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentity.Serialization.cs +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - [JsonConverter(typeof(SystemAssignedServiceIdentityConverter))] - public partial class SystemAssignedServiceIdentity : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SystemAssignedServiceIdentity)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(PrincipalId)) - { - writer.WritePropertyName("principalId"u8); - writer.WriteStringValue(PrincipalId.Value); - } - if (options.Format != "W" && Optional.IsDefined(TenantId)) - { - writer.WritePropertyName("tenantId"u8); - writer.WriteStringValue(TenantId.Value); - } - writer.WritePropertyName("type"u8); - writer.WriteStringValue(SystemAssignedServiceIdentityType.ToString()); - } - - SystemAssignedServiceIdentity IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SystemAssignedServiceIdentity)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeSystemAssignedServiceIdentity(document.RootElement, options); - } - - internal static SystemAssignedServiceIdentity DeserializeSystemAssignedServiceIdentity(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - Guid? principalId = default; - Guid? tenantId = default; - SystemAssignedServiceIdentityType type = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("principalId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - principalId = property.Value.GetGuid(); - continue; - } - if (property.NameEquals("tenantId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - tenantId = property.Value.GetGuid(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new SystemAssignedServiceIdentityType(property.Value.GetString()); - continue; - } - } - return new SystemAssignedServiceIdentity(principalId, tenantId, type); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PrincipalId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" principalId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PrincipalId)) - { - builder.Append(" principalId: "); - builder.AppendLine($"'{PrincipalId.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TenantId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenantId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TenantId)) - { - builder.Append(" tenantId: "); - builder.AppendLine($"'{TenantId.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemAssignedServiceIdentityType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" type: "); - builder.AppendLine(propertyOverride); - } - else - { - builder.Append(" type: "); - builder.AppendLine($"'{SystemAssignedServiceIdentityType.ToString()}'"); - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(SystemAssignedServiceIdentity)} does not support writing '{options.Format}' format."); - } - } - - SystemAssignedServiceIdentity IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeSystemAssignedServiceIdentity(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(SystemAssignedServiceIdentity)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class SystemAssignedServiceIdentityConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, SystemAssignedServiceIdentity model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model, ModelSerializationExtensions.WireOptions); - } - - public override SystemAssignedServiceIdentity Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeSystemAssignedServiceIdentity(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentity.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentity.cs deleted file mode 100644 index f7feea87c2..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentity.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// Managed service identity (either system assigned, or none). - [PropertyReferenceType] - public partial class SystemAssignedServiceIdentity - { - /// Initializes a new instance of for deserialization. - internal SystemAssignedServiceIdentity() - { - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentityType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentityType.cs deleted file mode 100644 index ab44e79a42..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentityType.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Models -{ - /// Type of managed service identity (either system assigned, or none). - public readonly partial struct SystemAssignedServiceIdentityType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public SystemAssignedServiceIdentityType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string NoneValue = "None"; - private const string SystemAssignedValue = "SystemAssigned"; - - /// None. - public static SystemAssignedServiceIdentityType None { get; } = new SystemAssignedServiceIdentityType(NoneValue); - /// SystemAssigned. - public static SystemAssignedServiceIdentityType SystemAssigned { get; } = new SystemAssignedServiceIdentityType(SystemAssignedValue); - /// Determines if two values are the same. - public static bool operator ==(SystemAssignedServiceIdentityType left, SystemAssignedServiceIdentityType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(SystemAssignedServiceIdentityType left, SystemAssignedServiceIdentityType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator SystemAssignedServiceIdentityType(string value) => new SystemAssignedServiceIdentityType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is SystemAssignedServiceIdentityType other && Equals(other); - /// - public bool Equals(SystemAssignedServiceIdentityType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemData.Serialization.cs deleted file mode 100644 index 513fa91320..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemData.Serialization.cs +++ /dev/null @@ -1,326 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - [JsonConverter(typeof(SystemDataConverter))] - public partial class SystemData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SystemData)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(CreatedBy)) - { - writer.WritePropertyName("createdBy"u8); - writer.WriteStringValue(CreatedBy); - } - if (options.Format != "W" && Optional.IsDefined(CreatedByType)) - { - writer.WritePropertyName("createdByType"u8); - writer.WriteStringValue(CreatedByType.Value.ToString()); - } - if (options.Format != "W" && Optional.IsDefined(CreatedOn)) - { - writer.WritePropertyName("createdAt"u8); - writer.WriteStringValue(CreatedOn.Value, "O"); - } - if (options.Format != "W" && Optional.IsDefined(LastModifiedBy)) - { - writer.WritePropertyName("lastModifiedBy"u8); - writer.WriteStringValue(LastModifiedBy); - } - if (options.Format != "W" && Optional.IsDefined(LastModifiedByType)) - { - writer.WritePropertyName("lastModifiedByType"u8); - writer.WriteStringValue(LastModifiedByType.Value.ToString()); - } - if (options.Format != "W" && Optional.IsDefined(LastModifiedOn)) - { - writer.WritePropertyName("lastModifiedAt"u8); - writer.WriteStringValue(LastModifiedOn.Value, "O"); - } - } - - SystemData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SystemData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeSystemData(document.RootElement, options); - } - - internal static SystemData DeserializeSystemData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string createdBy = default; - CreatedByType? createdByType = default; - DateTimeOffset? createdAt = default; - string lastModifiedBy = default; - CreatedByType? lastModifiedByType = default; - DateTimeOffset? lastModifiedAt = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("createdBy"u8)) - { - createdBy = property.Value.GetString(); - continue; - } - if (property.NameEquals("createdByType"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - createdByType = new CreatedByType(property.Value.GetString()); - continue; - } - if (property.NameEquals("createdAt"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - createdAt = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("lastModifiedBy"u8)) - { - lastModifiedBy = property.Value.GetString(); - continue; - } - if (property.NameEquals("lastModifiedByType"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - lastModifiedByType = new CreatedByType(property.Value.GetString()); - continue; - } - if (property.NameEquals("lastModifiedAt"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - lastModifiedAt = property.Value.GetDateTimeOffset("O"); - continue; - } - } - return new SystemData( - createdBy, - createdByType, - createdAt, - lastModifiedBy, - lastModifiedByType, - lastModifiedAt); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(CreatedBy), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" createdBy: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(CreatedBy)) - { - builder.Append(" createdBy: "); - if (CreatedBy.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{CreatedBy}'''"); - } - else - { - builder.AppendLine($"'{CreatedBy}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(CreatedByType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" createdByType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(CreatedByType)) - { - builder.Append(" createdByType: "); - builder.AppendLine($"'{CreatedByType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(CreatedOn), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" createdAt: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(CreatedOn)) - { - builder.Append(" createdAt: "); - var formattedDateTimeString = TypeFormatters.ToString(CreatedOn.Value, "o"); - builder.AppendLine($"'{formattedDateTimeString}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(LastModifiedBy), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" lastModifiedBy: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(LastModifiedBy)) - { - builder.Append(" lastModifiedBy: "); - if (LastModifiedBy.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{LastModifiedBy}'''"); - } - else - { - builder.AppendLine($"'{LastModifiedBy}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(LastModifiedByType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" lastModifiedByType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(LastModifiedByType)) - { - builder.Append(" lastModifiedByType: "); - builder.AppendLine($"'{LastModifiedByType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(LastModifiedOn), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" lastModifiedAt: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(LastModifiedOn)) - { - builder.Append(" lastModifiedAt: "); - var formattedDateTimeString = TypeFormatters.ToString(LastModifiedOn.Value, "o"); - builder.AppendLine($"'{formattedDateTimeString}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(SystemData)} does not support writing '{options.Format}' format."); - } - } - - SystemData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeSystemData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(SystemData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class SystemDataConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, SystemData model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model, ModelSerializationExtensions.WireOptions); - } - - public override SystemData Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeSystemData(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemData.cs deleted file mode 100644 index 14d762f3b5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/SystemData.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// Metadata pertaining to creation and last modification of the resource. - [PropertyReferenceType] - public partial class SystemData - { - /// Initializes a new instance of . - [InitializationConstructor] - public SystemData() - { - } - - /// Initializes a new instance of . - /// The identity that created the resource. - /// The type of identity that created the resource. - /// The timestamp of resource creation (UTC). - /// The identity that last modified the resource. - /// The type of identity that last modified the resource. - /// The timestamp of resource last modification (UTC). - [SerializationConstructor] - internal SystemData(string createdBy, CreatedByType? createdByType, DateTimeOffset? createdOn, string lastModifiedBy, CreatedByType? lastModifiedByType, DateTimeOffset? lastModifiedOn) - { - CreatedBy = createdBy; - CreatedByType = createdByType; - CreatedOn = createdOn; - LastModifiedBy = lastModifiedBy; - LastModifiedByType = lastModifiedByType; - LastModifiedOn = lastModifiedOn; - } - - /// The identity that created the resource. - [WirePath("createdBy")] - public string CreatedBy { get; } - /// The type of identity that created the resource. - [WirePath("createdByType")] - public CreatedByType? CreatedByType { get; } - /// The timestamp of resource creation (UTC). - [WirePath("createdAt")] - public DateTimeOffset? CreatedOn { get; } - /// The identity that last modified the resource. - [WirePath("lastModifiedBy")] - public string LastModifiedBy { get; } - /// The type of identity that last modified the resource. - [WirePath("lastModifiedByType")] - public CreatedByType? LastModifiedByType { get; } - /// The timestamp of resource last modification (UTC). - [WirePath("lastModifiedAt")] - public DateTimeOffset? LastModifiedOn { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/TrackedResourceData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/TrackedResourceData.Serialization.cs deleted file mode 100644 index a6af3ca008..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/TrackedResourceData.Serialization.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Models -{ - public partial class TrackedResourceData - { - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - base.JsonModelWriteCore(writer, options); - if (Optional.IsCollectionDefined(Tags)) - { - writer.WritePropertyName("tags"u8); - writer.WriteStartObject(); - foreach (var item in Tags) - { - writer.WritePropertyName(item.Key); - writer.WriteStringValue(item.Value); - } - writer.WriteEndObject(); - } - writer.WritePropertyName("location"u8); - writer.WriteStringValue(Location); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/TrackedResourceData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/TrackedResourceData.cs deleted file mode 100644 index 741469301d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/TrackedResourceData.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. - [ReferenceType(new string[] { "SystemData" })] - public abstract partial class TrackedResourceData : ResourceData - { - /// Initializes a new instance of . - /// The geo-location where the resource lives. - [InitializationConstructor] - protected TrackedResourceData(AzureLocation location) - { - Tags = new ChangeTrackingDictionary(); - Location = location; - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// Resource tags. - /// The geo-location where the resource lives. - [SerializationConstructor] - protected TrackedResourceData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, IDictionary tags, AzureLocation location) : base(id, name, resourceType, systemData) - { - Tags = tags; - Location = location; - } - - /// Initializes a new instance of for deserialization. - protected TrackedResourceData() - { - } - - /// Resource tags. - public IDictionary Tags { get; } - /// The geo-location where the resource lives. - public AzureLocation Location { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/UserAssignedIdentity.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/UserAssignedIdentity.Serialization.cs deleted file mode 100644 index ad78fdb6bc..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/UserAssignedIdentity.Serialization.cs +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - [JsonConverter(typeof(UserAssignedIdentityConverter))] - public partial class UserAssignedIdentity : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(UserAssignedIdentity)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(PrincipalId)) - { - writer.WritePropertyName("principalId"u8); - writer.WriteStringValue(PrincipalId.Value); - } - if (options.Format != "W" && Optional.IsDefined(ClientId)) - { - writer.WritePropertyName("clientId"u8); - writer.WriteStringValue(ClientId.Value); - } - } - - UserAssignedIdentity IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(UserAssignedIdentity)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeUserAssignedIdentity(document.RootElement, options); - } - - internal static UserAssignedIdentity DeserializeUserAssignedIdentity(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - Guid? principalId = default; - Guid? clientId = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("principalId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - principalId = property.Value.GetGuid(); - continue; - } - if (property.NameEquals("clientId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - clientId = property.Value.GetGuid(); - continue; - } - } - return new UserAssignedIdentity(principalId, clientId); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PrincipalId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" principalId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PrincipalId)) - { - builder.Append(" principalId: "); - builder.AppendLine($"'{PrincipalId.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ClientId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" clientId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ClientId)) - { - builder.Append(" clientId: "); - builder.AppendLine($"'{ClientId.Value.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(UserAssignedIdentity)} does not support writing '{options.Format}' format."); - } - } - - UserAssignedIdentity IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeUserAssignedIdentity(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(UserAssignedIdentity)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class UserAssignedIdentityConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, UserAssignedIdentity model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model, ModelSerializationExtensions.WireOptions); - } - - public override UserAssignedIdentity Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeUserAssignedIdentity(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/UserAssignedIdentity.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/UserAssignedIdentity.cs deleted file mode 100644 index 727197fddd..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Common/Generated/Models/UserAssignedIdentity.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using Azure.Core; - -namespace Azure.ResourceManager.Models -{ - /// User assigned identity properties. - [PropertyReferenceType] - public partial class UserAssignedIdentity - { - /// Initializes a new instance of . - [InitializationConstructor] - public UserAssignedIdentity() - { - } - - /// Initializes a new instance of . - /// The principal ID of the assigned identity. - /// The client ID of the assigned identity. - [SerializationConstructor] - internal UserAssignedIdentity(Guid? principalId, Guid? clientId) - { - PrincipalId = principalId; - ClientId = clientId; - } - - /// The principal ID of the assigned identity. - [WirePath("principalId")] - public Guid? PrincipalId { get; } - /// The client ID of the assigned identity. - [WirePath("clientId")] - public Guid? ClientId { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Directory.Build.props b/tests/dotnet-upgrade/dotnet-aot-compat/before/Directory.Build.props deleted file mode 100644 index 8c119d5413..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Directory.Build.props +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Directory.Packages.props b/tests/dotnet-upgrade/dotnet-aot-compat/before/Directory.Packages.props deleted file mode 100644 index 5fc7d2a08a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Directory.Packages.props +++ /dev/null @@ -1,10 +0,0 @@ - - - true - - - - - - - diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ExperimentalAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ExperimentalAttribute.cs deleted file mode 100644 index 9465ac0f52..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ExperimentalAttribute.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#if !NET8_0_OR_GREATER - -#nullable enable - -namespace System.Diagnostics.CodeAnalysis -{ - /// - /// Indicates that an API is experimental and it may change in the future. - /// - /// - /// This attribute allows call sites to be flagged with a diagnostic that indicates that an experimental - /// feature is used. Authors can use this attribute to ship preview features in their assemblies. - /// - [AttributeUsage(AttributeTargets.Assembly | - AttributeTargets.Module | - AttributeTargets.Class | - AttributeTargets.Struct | - AttributeTargets.Enum | - AttributeTargets.Constructor | - AttributeTargets.Method | - AttributeTargets.Property | - AttributeTargets.Field | - AttributeTargets.Event | - AttributeTargets.Interface | - AttributeTargets.Delegate, Inherited = false)] - internal sealed class ExperimentalAttribute : Attribute - { - /// - /// Initializes a new instance of the class, specifying the ID that the compiler will use - /// when reporting a use of the API the attribute applies to. - /// - /// The ID that the compiler will use when reporting a use of the API the attribute applies to. - public ExperimentalAttribute(string diagnosticId) - { - DiagnosticId = diagnosticId; - } - - /// - /// Gets the ID that the compiler will use when reporting a use of the API the attribute applies to. - /// - /// The unique diagnostic ID. - /// - /// The diagnostic ID is shown in build output for warnings and errors. - /// This property represents the unique ID that can be used to suppress the warnings or errors, if needed. - /// - public string DiagnosticId { get; } - - /// - /// Gets or sets the URL for corresponding documentation. - /// The API accepts a format string instead of an actual URL, creating a generic URL that includes the diagnostic ID. - /// - /// The format string that represents a URL to corresponding documentation. - /// An example format string is https://contoso.com/obsoletion-warnings/{0}. - public string? UrlFormat { get; set; } - } -} -#endif diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Extensions/ArmClientBuilderExtensions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Extensions/ArmClientBuilderExtensions.cs deleted file mode 100644 index 6b08a9df52..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Extensions/ArmClientBuilderExtensions.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.Diagnostics.CodeAnalysis; -using Azure.Core.Extensions; -using Azure.ResourceManager; - -namespace Microsoft.Extensions.Azure -{ - /// - /// Extension methods to add client to clients builder. - /// - public static class ArmClientBuilderExtensions - { - /// - /// Registers an instance with the provided - /// - public static IAzureClientBuilder AddArmClient(this TBuilder builder, string defaultSubscription) - where TBuilder : IAzureClientFactoryBuilderWithCredential - { - return builder.RegisterClientFactory((options, cred) => new ArmClient(cred, defaultSubscription, options)); - } - - /// - /// Registers an instance with connection options loaded from the provided instance. - /// - public static IAzureClientBuilder AddArmClient(this TBuilder builder, TConfiguration configuration) - where TBuilder : IAzureClientFactoryBuilderWithConfiguration - { - return builder.RegisterClientFactory(configuration); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/GenericOperationSource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/GenericOperationSource.cs deleted file mode 100644 index cb5c47a9f5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/GenericOperationSource.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Diagnostics.CodeAnalysis; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; - -namespace Azure.ResourceManager -{ - internal class GenericOperationSource : IOperationSource - { - private readonly ArmClient _client; - private readonly bool _isResource; - - public GenericOperationSource(ArmClient client, bool isResource) - { - _client = client; - _isResource = isResource; - } - - T IOperationSource.CreateResult(Response response, CancellationToken cancellationToken) - => CreateResult(response); - - ValueTask IOperationSource.CreateResultAsync(Response response, CancellationToken cancellationToken) - => new ValueTask(CreateResult(response)); - - private T CreateResult(Response response) - { - // This call will never be invoked with a collection of models, so we can safely disable the warning -#pragma warning disable AZC0150 // Use ModelReaderWriter overloads with ModelReaderWriterContext - object data = ModelReaderWriter.Read(response.Content, typeof(T)); -#pragma warning restore AZC0150 // Use ModelReaderWriter overloads with ModelReaderWriterContext - return _isResource - ? (T)Activator.CreateInstance(typeof(T), BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { _client, data }, null) - : (T)data; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Custom/HelperSuppressions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Custom/HelperSuppressions.cs deleted file mode 100644 index dfe77b4da6..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Custom/HelperSuppressions.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using Azure.Core; - -[assembly: CodeGenSuppressType("Azure.ResourceManager.Optional")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.ChangeTrackingList")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.RequestContentHelper")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.Argument")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.Utf8JsonRequestContent")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.ChangeTrackingDictionary")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.ModelSerializationExtensions")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.BicepSerializationHelpers")] diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Custom/ManagementGroupResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Custom/ManagementGroupResource.cs deleted file mode 100644 index 809c4fff69..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Custom/ManagementGroupResource.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ComponentModel; -using System.Threading; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups.Models; - -[assembly:CodeGenSuppressType("SearchOptions")] -[assembly:CodeGenSuppressType("EntityViewOptions")] -[assembly:CodeGenSuppressType("TenantExtensions")] // Moved code to Custom/Tenant -[assembly:CodeGenSuppressType("AzureAsyncOperationResults")] -[assembly:CodeGenSuppressType("ErrorResponse")] -[assembly:CodeGenSuppressType("ErrorDetails")] // No target and additionalInfo properties, therefore it's not replaced by common type -[assembly:CodeGenSuppressType("ManagementGroupUpdateOperation")] -namespace Azure.ResourceManager.ManagementGroups -{ - /// A Class representing a ManagementGroup along with the instance operations that can be performed on it. - public partial class ManagementGroupResource : ArmResource - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Custom/Models/ManagementGroupNameAvailabilityContent.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Custom/Models/ManagementGroupNameAvailabilityContent.cs deleted file mode 100644 index a033177eb0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Custom/Models/ManagementGroupNameAvailabilityContent.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupNameAvailabilityContent - { - /// Initializes a new instance of ManagementGroupNameAvailabilityContent. - public ManagementGroupNameAvailabilityContent() - { - ResourceType = "Microsoft.Management/managementGroups"; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Extensions/ArmClient.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Extensions/ArmClient.cs deleted file mode 100644 index 6881f263fc..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Extensions/ArmClient.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using Azure.Core; -using Azure.ResourceManager.ManagementGroups; - -namespace Azure.ResourceManager -{ - public partial class ArmClient - { - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual ManagementGroupResource GetManagementGroupResource(ResourceIdentifier id) - { - ManagementGroupResource.ValidateResourceId(id); - return new ManagementGroupResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual ManagementGroupSubscriptionResource GetManagementGroupSubscriptionResource(ResourceIdentifier id) - { - ManagementGroupSubscriptionResource.ValidateResourceId(id); - return new ManagementGroupSubscriptionResource(this, id); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Extensions/TenantResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Extensions/TenantResource.cs deleted file mode 100644 index 457e521a66..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Extensions/TenantResource.cs +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.ResourceManager.ManagementGroups; -using Azure.ResourceManager.ManagementGroups.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class TenantResource - { - /// Gets a collection of ManagementGroupResources in the TenantResource. - /// An object representing collection of ManagementGroupResources and their operations over a ManagementGroupResource. - public virtual ManagementGroupCollection GetManagementGroups() - { - return GetCachedClient(client => new ManagementGroupCollection(client, Id)); - } - - /// - /// Get the details of the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetManagementGroupAsync(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - return await GetManagementGroups().GetAsync(groupId, expand, recurse, filter, cacheControl, cancellationToken).ConfigureAwait(false); - } - - /// - /// Get the details of the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetManagementGroup(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - return GetManagementGroups().Get(groupId, expand, recurse, filter, cacheControl, cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Internal/WirePathAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Internal/WirePathAttribute.cs deleted file mode 100644 index 9f3fd65374..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Internal/WirePathAttribute.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.ManagementGroups -{ - [AttributeUsage(AttributeTargets.Property)] - internal class WirePathAttribute : Attribute - { - private string _wirePath; - - public WirePathAttribute(string wirePath) - { - _wirePath = wirePath; - } - - public override string ToString() - { - return _wirePath; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupOperationSource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupOperationSource.cs deleted file mode 100644 index b7ed659f6a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupOperationSource.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.ClientModel.Primitives; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups -{ - internal class ManagementGroupOperationSource : IOperationSource - { - private readonly ArmClient _client; - - internal ManagementGroupOperationSource(ArmClient client) - { - _client = client; - } - - ManagementGroupResource IOperationSource.CreateResult(Response response, CancellationToken cancellationToken) - { - var data = ModelReaderWriter.Read(response.Content, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default); - return new ManagementGroupResource(_client, data); - } - - async ValueTask IOperationSource.CreateResultAsync(Response response, CancellationToken cancellationToken) - { - var data = ModelReaderWriter.Read(response.Content, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default); - return await Task.FromResult(new ManagementGroupResource(_client, data)).ConfigureAwait(false); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperation.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperation.cs deleted file mode 100644 index 5e967bcda8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperation.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.ManagementGroups -{ -#pragma warning disable SA1649 // File name should match first type name - internal class ManagementGroupsArmOperation : ArmOperation -#pragma warning restore SA1649 // File name should match first type name - { - private readonly OperationInternal _operation; - private readonly RehydrationToken? _completeRehydrationToken; - private readonly NextLinkOperationImplementation _nextLinkOperation; - private readonly string _operationId; - - /// Initializes a new instance of ManagementGroupsArmOperation for mocking. - protected ManagementGroupsArmOperation() - { - } - - internal ManagementGroupsArmOperation(Response response, RehydrationToken? rehydrationToken = null) - { - _operation = OperationInternal.Succeeded(response); - _completeRehydrationToken = rehydrationToken; - _operationId = GetOperationId(rehydrationToken); - } - - internal ManagementGroupsArmOperation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response, OperationFinalStateVia finalStateVia, bool skipApiVersionOverride = false, string apiVersionOverrideValue = null) - { - var nextLinkOperation = NextLinkOperationImplementation.Create(pipeline, request.Method, request.Uri.ToUri(), response, finalStateVia, skipApiVersionOverride, apiVersionOverrideValue); - if (nextLinkOperation is NextLinkOperationImplementation nextLinkOperationValue) - { - _nextLinkOperation = nextLinkOperationValue; - _operationId = _nextLinkOperation.OperationId; - } - else - { - _completeRehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(request.Method, request.Uri.ToUri(), response, finalStateVia); - _operationId = GetOperationId(_completeRehydrationToken); - } - _operation = new OperationInternal(nextLinkOperation, clientDiagnostics, response, "ManagementGroupsArmOperation", fallbackStrategy: new SequentialDelayStrategy()); - } - - private string GetOperationId(RehydrationToken? rehydrationToken) - { - if (rehydrationToken is null) - { - return null; - } - var lroDetails = ModelReaderWriter.Write(rehydrationToken, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default).ToObjectFromJson>(); - return lroDetails["id"]; - } - /// - public override string Id => _operationId ?? NextLinkOperationImplementation.NotSet; - - /// - public override RehydrationToken? GetRehydrationToken() => _nextLinkOperation?.GetRehydrationToken() ?? _completeRehydrationToken; - - /// - public override bool HasCompleted => _operation.HasCompleted; - - /// - public override Response GetRawResponse() => _operation.RawResponse; - - /// - public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); - - /// - public override ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); - - /// - public override Response WaitForCompletionResponse(CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponse(cancellationToken); - - /// - public override Response WaitForCompletionResponse(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponse(pollingInterval, cancellationToken); - - /// - public override ValueTask WaitForCompletionResponseAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponseAsync(cancellationToken); - - /// - public override ValueTask WaitForCompletionResponseAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponseAsync(pollingInterval, cancellationToken); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperationOfT.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperationOfT.cs deleted file mode 100644 index aa441fcede..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperationOfT.cs +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.ManagementGroups -{ -#pragma warning disable SA1649 // File name should match first type name - internal class ManagementGroupsArmOperation : ArmOperation -#pragma warning restore SA1649 // File name should match first type name - { - private readonly OperationInternal _operation; - private readonly RehydrationToken? _completeRehydrationToken; - private readonly NextLinkOperationImplementation _nextLinkOperation; - private readonly string _operationId; - - /// Initializes a new instance of ManagementGroupsArmOperation for mocking. - protected ManagementGroupsArmOperation() - { - } - - internal ManagementGroupsArmOperation(Response response, RehydrationToken? rehydrationToken = null) - { - _operation = OperationInternal.Succeeded(response.GetRawResponse(), response.Value); - _completeRehydrationToken = rehydrationToken; - _operationId = GetOperationId(rehydrationToken); - } - - internal ManagementGroupsArmOperation(IOperationSource source, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response, OperationFinalStateVia finalStateVia, bool skipApiVersionOverride = false, string apiVersionOverrideValue = null) - { - var nextLinkOperation = NextLinkOperationImplementation.Create(pipeline, request.Method, request.Uri.ToUri(), response, finalStateVia, skipApiVersionOverride, apiVersionOverrideValue); - if (nextLinkOperation is NextLinkOperationImplementation nextLinkOperationValue) - { - _nextLinkOperation = nextLinkOperationValue; - _operationId = _nextLinkOperation.OperationId; - } - else - { - _completeRehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(request.Method, request.Uri.ToUri(), response, finalStateVia); - _operationId = GetOperationId(_completeRehydrationToken); - } - _operation = new OperationInternal(NextLinkOperationImplementation.Create(source, nextLinkOperation), clientDiagnostics, response, "ManagementGroupsArmOperation", fallbackStrategy: new SequentialDelayStrategy()); - } - - private string GetOperationId(RehydrationToken? rehydrationToken) - { - if (rehydrationToken is null) - { - return null; - } - var lroDetails = ModelReaderWriter.Write(rehydrationToken, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default).ToObjectFromJson>(); - return lroDetails["id"]; - } - /// - public override string Id => _operationId ?? NextLinkOperationImplementation.NotSet; - - /// - public override RehydrationToken? GetRehydrationToken() => _nextLinkOperation?.GetRehydrationToken() ?? _completeRehydrationToken; - - /// - public override T Value => _operation.Value; - - /// - public override bool HasValue => _operation.HasValue; - - /// - public override bool HasCompleted => _operation.HasCompleted; - - /// - public override Response GetRawResponse() => _operation.RawResponse; - - /// - public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); - - /// - public override ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); - - /// - public override Response WaitForCompletion(CancellationToken cancellationToken = default) => _operation.WaitForCompletion(cancellationToken); - - /// - public override Response WaitForCompletion(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletion(pollingInterval, cancellationToken); - - /// - public override ValueTask> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken); - - /// - public override ValueTask> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupCollection.cs deleted file mode 100644 index 888276d7e4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupCollection.cs +++ /dev/null @@ -1,688 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups.Models; -using Azure.ResourceManager.Resources; - -namespace Azure.ResourceManager.ManagementGroups -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetManagementGroups method from an instance of . - /// - public partial class ManagementGroupCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _managementGroupClientDiagnostics; - private readonly ManagementGroupsRestOperations _managementGroupRestClient; - private readonly ClientDiagnostics _entitiesClientDiagnostics; - private readonly EntitiesRestOperations _entitiesRestClient; - - /// Initializes a new instance of the class for mocking. - protected ManagementGroupCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal ManagementGroupCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementGroupClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.ManagementGroups", ManagementGroupResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ManagementGroupResource.ResourceType, out string managementGroupApiVersion); - _managementGroupRestClient = new ManagementGroupsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementGroupApiVersion); - _entitiesClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.ManagementGroups", ProviderConstants.DefaultProviderNamespace, Diagnostics); - _entitiesRestClient = new EntitiesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != TenantResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, TenantResource.ResourceType), nameof(id)); - } - - /// - /// Create or update a management group. - /// If a management group is already created and a subsequent create request is issued with different properties, the management group properties will be updated. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Management Group ID. - /// Management group creation parameters. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string groupId, ManagementGroupCreateOrUpdateContent content, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNull(content, nameof(content)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _managementGroupRestClient.CreateOrUpdateAsync(groupId, content, cacheControl, cancellationToken).ConfigureAwait(false); - var operation = new ManagementGroupsArmOperation(new ManagementGroupOperationSource(Client), _managementGroupClientDiagnostics, Pipeline, _managementGroupRestClient.CreateCreateOrUpdateRequest(groupId, content, cacheControl).Request, response, OperationFinalStateVia.AzureAsyncOperation); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Create or update a management group. - /// If a management group is already created and a subsequent create request is issued with different properties, the management group properties will be updated. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Management Group ID. - /// Management group creation parameters. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string groupId, ManagementGroupCreateOrUpdateContent content, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNull(content, nameof(content)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = _managementGroupRestClient.CreateOrUpdate(groupId, content, cacheControl, cancellationToken); - var operation = new ManagementGroupsArmOperation(new ManagementGroupOperationSource(Client), _managementGroupClientDiagnostics, Pipeline, _managementGroupRestClient.CreateCreateOrUpdateRequest(groupId, content, cacheControl).Request, response, OperationFinalStateVia.AzureAsyncOperation); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Get the details of the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.Get"); - scope.Start(); - try - { - var response = await _managementGroupRestClient.GetAsync(groupId, expand, recurse, filter, cacheControl, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Get the details of the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.Get"); - scope.Start(); - try - { - var response = _managementGroupRestClient.Get(groupId, expand, recurse, filter, cacheControl, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// List management groups for the authenticated user. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups - /// - /// - /// Operation Id - /// ManagementGroups_List - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string cacheControl = null, string skipToken = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupRestClient.CreateListRequest(cacheControl, skipToken); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupRestClient.CreateListNextPageRequest(nextLink, cacheControl, skipToken); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new ManagementGroupResource(Client, ManagementGroupData.DeserializeManagementGroupData(e)), _managementGroupClientDiagnostics, Pipeline, "ManagementGroupCollection.GetAll", "value", "@nextLink", cancellationToken); - } - - /// - /// List management groups for the authenticated user. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups - /// - /// - /// Operation Id - /// ManagementGroups_List - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string cacheControl = null, string skipToken = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupRestClient.CreateListRequest(cacheControl, skipToken); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupRestClient.CreateListNextPageRequest(nextLink, cacheControl, skipToken); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new ManagementGroupResource(Client, ManagementGroupData.DeserializeManagementGroupData(e)), _managementGroupClientDiagnostics, Pipeline, "ManagementGroupCollection.GetAll", "value", "@nextLink", cancellationToken); - } - - /// - /// Checks if the specified management group name is valid and unique - /// - /// - /// Request Path - /// /providers/Microsoft.Management/checkNameAvailability - /// - /// - /// Operation Id - /// ManagementGroups_CheckNameAvailability - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management group name availability check parameters. - /// The cancellation token to use. - /// is null. - public virtual async Task> CheckNameAvailabilityAsync(ManagementGroupNameAvailabilityContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.CheckNameAvailability"); - scope.Start(); - try - { - var response = await _managementGroupRestClient.CheckNameAvailabilityAsync(content, cancellationToken).ConfigureAwait(false); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks if the specified management group name is valid and unique - /// - /// - /// Request Path - /// /providers/Microsoft.Management/checkNameAvailability - /// - /// - /// Operation Id - /// ManagementGroups_CheckNameAvailability - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management group name availability check parameters. - /// The cancellation token to use. - /// is null. - public virtual Response CheckNameAvailability(ManagementGroupNameAvailabilityContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.CheckNameAvailability"); - scope.Start(); - try - { - var response = _managementGroupRestClient.CheckNameAvailability(content, cancellationToken); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// List all entities (Management Groups, Subscriptions, etc.) for the authenticated user. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/getEntities - /// - /// - /// Operation Id - /// Entities_List - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// - /// A property bag which contains all the parameters of this method except the LRO qualifier and request context parameter. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetEntitiesAsync(ManagementGroupCollectionGetEntitiesOptions options, CancellationToken cancellationToken = default) - { - options ??= new ManagementGroupCollectionGetEntitiesOptions(); - - HttpMessage FirstPageRequest(int? pageSizeHint) => _entitiesRestClient.CreateListRequest(options.SkipToken, options.Skip, options.Top, options.Select, options.Search, options.Filter, options.View, options.GroupName, options.CacheControl); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _entitiesRestClient.CreateListNextPageRequest(nextLink, options.SkipToken, options.Skip, options.Top, options.Select, options.Search, options.Filter, options.View, options.GroupName, options.CacheControl); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => EntityData.DeserializeEntityData(e), _entitiesClientDiagnostics, Pipeline, "ManagementGroupCollection.GetEntities", "value", "nextLink", cancellationToken); - } - - /// - /// List all entities (Management Groups, Subscriptions, etc.) for the authenticated user. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/getEntities - /// - /// - /// Operation Id - /// Entities_List - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// - /// A property bag which contains all the parameters of this method except the LRO qualifier and request context parameter. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetEntities(ManagementGroupCollectionGetEntitiesOptions options, CancellationToken cancellationToken = default) - { - options ??= new ManagementGroupCollectionGetEntitiesOptions(); - - HttpMessage FirstPageRequest(int? pageSizeHint) => _entitiesRestClient.CreateListRequest(options.SkipToken, options.Skip, options.Top, options.Select, options.Search, options.Filter, options.View, options.GroupName, options.CacheControl); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _entitiesRestClient.CreateListNextPageRequest(nextLink, options.SkipToken, options.Skip, options.Top, options.Select, options.Search, options.Filter, options.View, options.GroupName, options.CacheControl); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => EntityData.DeserializeEntityData(e), _entitiesClientDiagnostics, Pipeline, "ManagementGroupCollection.GetEntities", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.Exists"); - scope.Start(); - try - { - var response = await _managementGroupRestClient.GetAsync(groupId, expand, recurse, filter, cacheControl, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.Exists"); - scope.Start(); - try - { - var response = _managementGroupRestClient.Get(groupId, expand, recurse, filter, cacheControl, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _managementGroupRestClient.GetAsync(groupId, expand, recurse, filter, cacheControl, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupCollection.GetIfExists"); - scope.Start(); - try - { - var response = _managementGroupRestClient.Get(groupId, expand, recurse, filter, cacheControl, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupData.Serialization.cs deleted file mode 100644 index 28569c1e7b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupData.Serialization.cs +++ /dev/null @@ -1,383 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.ManagementGroups.Models; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.ManagementGroups -{ - public partial class ManagementGroupData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (Optional.IsDefined(TenantId)) - { - writer.WritePropertyName("tenantId"u8); - writer.WriteStringValue(TenantId.Value); - } - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (Optional.IsDefined(Details)) - { - writer.WritePropertyName("details"u8); - writer.WriteObjectValue(Details, options); - } - if (Optional.IsCollectionDefined(Children)) - { - if (Children != null) - { - writer.WritePropertyName("children"u8); - writer.WriteStartArray(); - foreach (var item in Children) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - else - { - writer.WriteNull("children"); - } - } - writer.WriteEndObject(); - } - - ManagementGroupData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupData(document.RootElement, options); - } - - internal static ManagementGroupData DeserializeManagementGroupData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - Guid? tenantId = default; - string displayName = default; - ManagementGroupInfo details = default; - IReadOnlyList children = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("tenantId"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - tenantId = property0.Value.GetGuid(); - continue; - } - if (property0.NameEquals("displayName"u8)) - { - displayName = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("details"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - details = ManagementGroupInfo.DeserializeManagementGroupInfo(property0.Value, options); - continue; - } - if (property0.NameEquals("children"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - children = null; - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(ManagementGroupChildInfo.DeserializeManagementGroupChildInfo(item, options)); - } - children = array; - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupData( - id, - name, - type, - systemData, - tenantId, - displayName, - details, - children ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.Append(" properties:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TenantId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenantId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TenantId)) - { - builder.Append(" tenantId: "); - builder.AppendLine($"'{TenantId.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Details), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" details: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Details)) - { - builder.Append(" details: "); - BicepSerializationHelpers.AppendChildObject(builder, Details, options, 4, false, " details: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Children), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" children: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Children)) - { - if (Children.Any()) - { - builder.Append(" children: "); - builder.AppendLine("["); - foreach (var item in Children) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 6, true, " children: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine(" }"); - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementGroupData)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupData.cs deleted file mode 100644 index 5b5b364b1d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupData.cs +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.ManagementGroups.Models; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.ManagementGroups -{ - /// - /// A class representing the ManagementGroup data model. - /// The management group details. - /// - public partial class ManagementGroupData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagementGroupData() - { - Children = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000. - /// The friendly name of the management group. - /// The details of a management group. - /// The list of children. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, Guid? tenantId, string displayName, ManagementGroupInfo details, IReadOnlyList children, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - TenantId = tenantId; - DisplayName = displayName; - Details = details; - Children = children; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000. - [WirePath("properties.tenantId")] - public Guid? TenantId { get; } - /// The friendly name of the management group. - [WirePath("properties.displayName")] - public string DisplayName { get; } - /// The details of a management group. - [WirePath("properties.details")] - public ManagementGroupInfo Details { get; } - /// The list of children. - [WirePath("properties.children")] - public IReadOnlyList Children { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupResource.Serialization.cs deleted file mode 100644 index daf7ad8478..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.ManagementGroups -{ - public partial class ManagementGroupResource : IJsonModel - { - private static ManagementGroupData s_dataDeserializationInstance; - private static ManagementGroupData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - ManagementGroupData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - ManagementGroupData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupResource.cs deleted file mode 100644 index 596e9a0bbf..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupResource.cs +++ /dev/null @@ -1,505 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups.Models; -using Azure.ResourceManager.Resources; - -namespace Azure.ResourceManager.ManagementGroups -{ - /// - /// A Class representing a ManagementGroup along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetManagementGroupResource method. - /// Otherwise you can get one from its parent resource using the GetManagementGroup method. - /// - public partial class ManagementGroupResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The groupId. - public static ResourceIdentifier CreateResourceIdentifier(string groupId) - { - var resourceId = $"/providers/Microsoft.Management/managementGroups/{groupId}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _managementGroupClientDiagnostics; - private readonly ManagementGroupsRestOperations _managementGroupRestClient; - private readonly ManagementGroupData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Management/managementGroups"; - - /// Initializes a new instance of the class for mocking. - protected ManagementGroupResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal ManagementGroupResource(ArmClient client, ManagementGroupData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal ManagementGroupResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementGroupClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.ManagementGroups", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string managementGroupApiVersion); - _managementGroupRestClient = new ManagementGroupsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementGroupApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual ManagementGroupData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// Gets a collection of ManagementGroupSubscriptionResources in the ManagementGroup. - /// An object representing collection of ManagementGroupSubscriptionResources and their operations over a ManagementGroupSubscriptionResource. - public virtual ManagementGroupSubscriptionCollection GetManagementGroupSubscriptions() - { - return GetCachedClient(client => new ManagementGroupSubscriptionCollection(client, Id)); - } - - /// - /// Retrieves details about given subscription which is associated with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetManagementGroupSubscriptionAsync(string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - return await GetManagementGroupSubscriptions().GetAsync(subscriptionId, cacheControl, cancellationToken).ConfigureAwait(false); - } - - /// - /// Retrieves details about given subscription which is associated with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetManagementGroupSubscription(string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - return GetManagementGroupSubscriptions().Get(subscriptionId, cacheControl, cancellationToken); - } - - /// - /// Get the details of the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual async Task> GetAsync(ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupResource.Get"); - scope.Start(); - try - { - var response = await _managementGroupRestClient.GetAsync(Id.Name, expand, recurse, filter, cacheControl, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Get the details of the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Get - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual Response Get(ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupResource.Get"); - scope.Start(); - try - { - var response = _managementGroupRestClient.Get(Id.Name, expand, recurse, filter, cacheControl, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Delete management group. - /// If a management group contains child resources, the request will fail. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Delete - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual async Task DeleteAsync(WaitUntil waitUntil, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupResource.Delete"); - scope.Start(); - try - { - var response = await _managementGroupRestClient.DeleteAsync(Id.Name, cacheControl, cancellationToken).ConfigureAwait(false); - var operation = new ManagementGroupsArmOperation(_managementGroupClientDiagnostics, Pipeline, _managementGroupRestClient.CreateDeleteRequest(Id.Name, cacheControl).Request, response, OperationFinalStateVia.AzureAsyncOperation); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Delete management group. - /// If a management group contains child resources, the request will fail. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Delete - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupResource.Delete"); - scope.Start(); - try - { - var response = _managementGroupRestClient.Delete(Id.Name, cacheControl, cancellationToken); - var operation = new ManagementGroupsArmOperation(_managementGroupClientDiagnostics, Pipeline, _managementGroupRestClient.CreateDeleteRequest(Id.Name, cacheControl).Request, response, OperationFinalStateVia.AzureAsyncOperation); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Update a management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Update - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management group patch parameters. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(ManagementGroupPatch patch, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(patch, nameof(patch)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupResource.Update"); - scope.Start(); - try - { - var response = await _managementGroupRestClient.UpdateAsync(Id.Name, patch, cacheControl, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new ManagementGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Update a management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId} - /// - /// - /// Operation Id - /// ManagementGroups_Update - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Management group patch parameters. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - public virtual Response Update(ManagementGroupPatch patch, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(patch, nameof(patch)); - - using var scope = _managementGroupClientDiagnostics.CreateScope("ManagementGroupResource.Update"); - scope.Start(); - try - { - var response = _managementGroupRestClient.Update(Id.Name, patch, cacheControl, cancellationToken); - return Response.FromValue(new ManagementGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// List all entities that descend from a management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/descendants - /// - /// - /// Operation Id - /// ManagementGroups_GetDescendants - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetDescendantsAsync(string skipToken = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupRestClient.CreateGetDescendantsRequest(Id.Name, skipToken, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupRestClient.CreateGetDescendantsNextPageRequest(nextLink, Id.Name, skipToken, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => DescendantData.DeserializeDescendantData(e), _managementGroupClientDiagnostics, Pipeline, "ManagementGroupResource.GetDescendants", "value", "nextLink", cancellationToken); - } - - /// - /// List all entities that descend from a management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/descendants - /// - /// - /// Operation Id - /// ManagementGroups_GetDescendants - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetDescendants(string skipToken = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupRestClient.CreateGetDescendantsRequest(Id.Name, skipToken, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupRestClient.CreateGetDescendantsNextPageRequest(nextLink, Id.Name, skipToken, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => DescendantData.DeserializeDescendantData(e), _managementGroupClientDiagnostics, Pipeline, "ManagementGroupResource.GetDescendants", "value", "nextLink", cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionCollection.cs deleted file mode 100644 index 9f8a56d321..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionCollection.cs +++ /dev/null @@ -1,516 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.ManagementGroups -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetManagementGroupSubscriptions method from an instance of . - /// - public partial class ManagementGroupSubscriptionCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _managementGroupSubscriptionClientDiagnostics; - private readonly ManagementGroupSubscriptionsRestOperations _managementGroupSubscriptionRestClient; - - /// Initializes a new instance of the class for mocking. - protected ManagementGroupSubscriptionCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal ManagementGroupSubscriptionCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementGroupSubscriptionClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.ManagementGroups", ManagementGroupSubscriptionResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ManagementGroupSubscriptionResource.ResourceType, out string managementGroupSubscriptionApiVersion); - _managementGroupSubscriptionRestClient = new ManagementGroupSubscriptionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementGroupSubscriptionApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ManagementGroupResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ManagementGroupResource.ResourceType), nameof(id)); - } - - /// - /// Associates existing subscription with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_Create - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _managementGroupSubscriptionRestClient.CreateAsync(Id.Name, subscriptionId, cacheControl, cancellationToken).ConfigureAwait(false); - var uri = _managementGroupSubscriptionRestClient.CreateCreateRequestUri(Id.Name, subscriptionId, cacheControl); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ManagementGroupsArmOperation(Response.FromValue(new ManagementGroupSubscriptionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Associates existing subscription with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_Create - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = _managementGroupSubscriptionRestClient.Create(Id.Name, subscriptionId, cacheControl, cancellationToken); - var uri = _managementGroupSubscriptionRestClient.CreateCreateRequestUri(Id.Name, subscriptionId, cacheControl); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ManagementGroupsArmOperation(Response.FromValue(new ManagementGroupSubscriptionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Retrieves details about given subscription which is associated with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionCollection.Get"); - scope.Start(); - try - { - var response = await _managementGroupSubscriptionRestClient.GetSubscriptionAsync(Id.Name, subscriptionId, cacheControl, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupSubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Retrieves details about given subscription which is associated with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionCollection.Get"); - scope.Start(); - try - { - var response = _managementGroupSubscriptionRestClient.GetSubscription(Id.Name, subscriptionId, cacheControl, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupSubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Retrieves details about all subscriptions which are associated with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscriptionsUnderManagementGroup - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string skipToken = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupSubscriptionRestClient.CreateGetSubscriptionsUnderManagementGroupRequest(Id.Name, skipToken); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupSubscriptionRestClient.CreateGetSubscriptionsUnderManagementGroupNextPageRequest(nextLink, Id.Name, skipToken); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new ManagementGroupSubscriptionResource(Client, ManagementGroupSubscriptionData.DeserializeManagementGroupSubscriptionData(e)), _managementGroupSubscriptionClientDiagnostics, Pipeline, "ManagementGroupSubscriptionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Retrieves details about all subscriptions which are associated with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscriptionsUnderManagementGroup - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string skipToken = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupSubscriptionRestClient.CreateGetSubscriptionsUnderManagementGroupRequest(Id.Name, skipToken); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupSubscriptionRestClient.CreateGetSubscriptionsUnderManagementGroupNextPageRequest(nextLink, Id.Name, skipToken); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new ManagementGroupSubscriptionResource(Client, ManagementGroupSubscriptionData.DeserializeManagementGroupSubscriptionData(e)), _managementGroupSubscriptionClientDiagnostics, Pipeline, "ManagementGroupSubscriptionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionCollection.Exists"); - scope.Start(); - try - { - var response = await _managementGroupSubscriptionRestClient.GetSubscriptionAsync(Id.Name, subscriptionId, cacheControl, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionCollection.Exists"); - scope.Start(); - try - { - var response = _managementGroupSubscriptionRestClient.GetSubscription(Id.Name, subscriptionId, cacheControl, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _managementGroupSubscriptionRestClient.GetSubscriptionAsync(Id.Name, subscriptionId, cacheControl, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupSubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionCollection.GetIfExists"); - scope.Start(); - try - { - var response = _managementGroupSubscriptionRestClient.GetSubscription(Id.Name, subscriptionId, cacheControl, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupSubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionData.Serialization.cs deleted file mode 100644 index f616dc610d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionData.Serialization.cs +++ /dev/null @@ -1,377 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.ManagementGroups.Models; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.ManagementGroups -{ - public partial class ManagementGroupSubscriptionData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupSubscriptionData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (Optional.IsDefined(Tenant)) - { - writer.WritePropertyName("tenant"u8); - writer.WriteStringValue(Tenant); - } - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (Optional.IsDefined(Parent)) - { - if (Parent != null) - { - writer.WritePropertyName("parent"u8); - writer.WriteObjectValue(Parent, options); - } - else - { - writer.WriteNull("parent"); - } - } - if (Optional.IsDefined(State)) - { - writer.WritePropertyName("state"u8); - writer.WriteStringValue(State); - } - writer.WriteEndObject(); - } - - ManagementGroupSubscriptionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupSubscriptionData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupSubscriptionData(document.RootElement, options); - } - - internal static ManagementGroupSubscriptionData DeserializeManagementGroupSubscriptionData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - string tenant = default; - string displayName = default; - DescendantParentGroupInfo parent = default; - string state = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("tenant"u8)) - { - tenant = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("displayName"u8)) - { - displayName = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("parent"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - parent = null; - continue; - } - parent = DescendantParentGroupInfo.DeserializeDescendantParentGroupInfo(property0.Value, options); - continue; - } - if (property0.NameEquals("state"u8)) - { - state = property0.Value.GetString(); - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupSubscriptionData( - id, - name, - type, - systemData, - tenant, - displayName, - parent, - state, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.Append(" properties:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Tenant), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenant: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Tenant)) - { - builder.Append(" tenant: "); - if (Tenant.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Tenant}'''"); - } - else - { - builder.AppendLine($"'{Tenant}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue("ParentId", out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parent: "); - builder.AppendLine("{"); - builder.AppendLine(" parent: {"); - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - builder.AppendLine(" }"); - builder.AppendLine(" }"); - } - else - { - if (Optional.IsDefined(Parent)) - { - builder.Append(" parent: "); - BicepSerializationHelpers.AppendChildObject(builder, Parent, options, 4, false, " parent: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(State), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" state: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(State)) - { - builder.Append(" state: "); - if (State.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{State}'''"); - } - else - { - builder.AppendLine($"'{State}'"); - } - } - } - - builder.AppendLine(" }"); - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementGroupSubscriptionData)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupSubscriptionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupSubscriptionData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupSubscriptionData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionData.cs deleted file mode 100644 index 012a80ff0c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionData.cs +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.ManagementGroups.Models; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.ManagementGroups -{ - /// - /// A class representing the ManagementGroupSubscription data model. - /// The details of subscription under management group. - /// - public partial class ManagementGroupSubscriptionData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagementGroupSubscriptionData() - { - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The AAD Tenant ID associated with the subscription. For example, 00000000-0000-0000-0000-000000000000. - /// The friendly name of the subscription. - /// The ID of the parent management group. - /// The state of the subscription. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupSubscriptionData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, string tenant, string displayName, DescendantParentGroupInfo parent, string state, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - Tenant = tenant; - DisplayName = displayName; - Parent = parent; - State = state; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The AAD Tenant ID associated with the subscription. For example, 00000000-0000-0000-0000-000000000000. - [WirePath("properties.tenant")] - public string Tenant { get; } - /// The friendly name of the subscription. - [WirePath("properties.displayName")] - public string DisplayName { get; } - /// The ID of the parent management group. - internal DescendantParentGroupInfo Parent { get; } - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - [WirePath("properties.parent.id")] - public ResourceIdentifier ParentId - { - get => Parent?.Id; - } - - /// The state of the subscription. - [WirePath("properties.state")] - public string State { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionResource.Serialization.cs deleted file mode 100644 index 27395325f3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.ManagementGroups -{ - public partial class ManagementGroupSubscriptionResource : IJsonModel - { - private static ManagementGroupSubscriptionData s_dataDeserializationInstance; - private static ManagementGroupSubscriptionData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - ManagementGroupSubscriptionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - ManagementGroupSubscriptionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionResource.cs deleted file mode 100644 index 084663c338..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionResource.cs +++ /dev/null @@ -1,357 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.ManagementGroups -{ - /// - /// A Class representing a ManagementGroupSubscription along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetManagementGroupSubscriptionResource method. - /// Otherwise you can get one from its parent resource using the GetManagementGroupSubscription method. - /// - public partial class ManagementGroupSubscriptionResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The groupId. - /// The subscriptionId. - public static ResourceIdentifier CreateResourceIdentifier(string groupId, string subscriptionId) - { - var resourceId = $"/providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _managementGroupSubscriptionClientDiagnostics; - private readonly ManagementGroupSubscriptionsRestOperations _managementGroupSubscriptionRestClient; - private readonly ManagementGroupSubscriptionData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Management/managementGroups/subscriptions"; - - /// Initializes a new instance of the class for mocking. - protected ManagementGroupSubscriptionResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal ManagementGroupSubscriptionResource(ArmClient client, ManagementGroupSubscriptionData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal ManagementGroupSubscriptionResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementGroupSubscriptionClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.ManagementGroups", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string managementGroupSubscriptionApiVersion); - _managementGroupSubscriptionRestClient = new ManagementGroupSubscriptionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementGroupSubscriptionApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual ManagementGroupSubscriptionData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// Retrieves details about given subscription which is associated with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual async Task> GetAsync(string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionResource.Get"); - scope.Start(); - try - { - var response = await _managementGroupSubscriptionRestClient.GetSubscriptionAsync(Id.Parent.Name, Id.Name, cacheControl, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupSubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Retrieves details about given subscription which is associated with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_GetSubscription - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual Response Get(string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionResource.Get"); - scope.Start(); - try - { - var response = _managementGroupSubscriptionRestClient.GetSubscription(Id.Parent.Name, Id.Name, cacheControl, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupSubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// De-associates subscription from the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_Delete - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual async Task DeleteAsync(WaitUntil waitUntil, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionResource.Delete"); - scope.Start(); - try - { - var response = await _managementGroupSubscriptionRestClient.DeleteAsync(Id.Parent.Name, Id.Name, cacheControl, cancellationToken).ConfigureAwait(false); - var uri = _managementGroupSubscriptionRestClient.CreateDeleteRequestUri(Id.Parent.Name, Id.Name, cacheControl); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ManagementGroupsArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// De-associates subscription from the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_Delete - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionResource.Delete"); - scope.Start(); - try - { - var response = _managementGroupSubscriptionRestClient.Delete(Id.Parent.Name, Id.Name, cacheControl, cancellationToken); - var uri = _managementGroupSubscriptionRestClient.CreateDeleteRequestUri(Id.Parent.Name, Id.Name, cacheControl); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ManagementGroupsArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Associates existing subscription with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_Create - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual async Task> UpdateAsync(WaitUntil waitUntil, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionResource.Update"); - scope.Start(); - try - { - var response = await _managementGroupSubscriptionRestClient.CreateAsync(Id.Parent.Name, Id.Name, cacheControl, cancellationToken).ConfigureAwait(false); - var uri = _managementGroupSubscriptionRestClient.CreateCreateRequestUri(Id.Parent.Name, Id.Name, cacheControl); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ManagementGroupsArmOperation(Response.FromValue(new ManagementGroupSubscriptionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Associates existing subscription with the management group. - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// ManagementGroupSubscriptions_Create - /// - /// - /// Default Api Version - /// 2021-04-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public virtual ArmOperation Update(WaitUntil waitUntil, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupSubscriptionClientDiagnostics.CreateScope("ManagementGroupSubscriptionResource.Update"); - scope.Start(); - try - { - var response = _managementGroupSubscriptionRestClient.Create(Id.Parent.Name, Id.Name, cacheControl, cancellationToken); - var uri = _managementGroupSubscriptionRestClient.CreateCreateRequestUri(Id.Parent.Name, Id.Name, cacheControl); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ManagementGroupsArmOperation(Response.FromValue(new ManagementGroupSubscriptionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/CreateManagementGroupDetails.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/CreateManagementGroupDetails.Serialization.cs deleted file mode 100644 index 167dd7d592..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/CreateManagementGroupDetails.Serialization.cs +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class CreateManagementGroupDetails : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(CreateManagementGroupDetails)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Version)) - { - writer.WritePropertyName("version"u8); - writer.WriteNumberValue(Version.Value); - } - if (options.Format != "W" && Optional.IsDefined(UpdatedOn)) - { - writer.WritePropertyName("updatedTime"u8); - writer.WriteStringValue(UpdatedOn.Value, "O"); - } - if (options.Format != "W" && Optional.IsDefined(UpdatedBy)) - { - writer.WritePropertyName("updatedBy"u8); - writer.WriteStringValue(UpdatedBy); - } - if (Optional.IsDefined(Parent)) - { - writer.WritePropertyName("parent"u8); - writer.WriteObjectValue(Parent, options); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - CreateManagementGroupDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(CreateManagementGroupDetails)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeCreateManagementGroupDetails(document.RootElement, options); - } - - internal static CreateManagementGroupDetails DeserializeCreateManagementGroupDetails(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - int? version = default; - DateTimeOffset? updatedTime = default; - string updatedBy = default; - ManagementGroupParentCreateOptions parent = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("version"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - version = property.Value.GetInt32(); - continue; - } - if (property.NameEquals("updatedTime"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - updatedTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("updatedBy"u8)) - { - updatedBy = property.Value.GetString(); - continue; - } - if (property.NameEquals("parent"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - parent = ManagementGroupParentCreateOptions.DeserializeManagementGroupParentCreateOptions(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new CreateManagementGroupDetails(version, updatedTime, updatedBy, parent, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(CreateManagementGroupDetails)} does not support writing '{options.Format}' format."); - } - } - - CreateManagementGroupDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeCreateManagementGroupDetails(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(CreateManagementGroupDetails)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/CreateManagementGroupDetails.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/CreateManagementGroupDetails.cs deleted file mode 100644 index 6cfb0e466c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/CreateManagementGroupDetails.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The details of a management group used during creation. - public partial class CreateManagementGroupDetails - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public CreateManagementGroupDetails() - { - } - - /// Initializes a new instance of . - /// The version number of the object. - /// The date and time when this object was last updated. - /// The identity of the principal or process that updated the object. - /// (Optional) The ID of the parent management group used during creation. - /// Keeps track of any properties unknown to the library. - internal CreateManagementGroupDetails(int? version, DateTimeOffset? updatedOn, string updatedBy, ManagementGroupParentCreateOptions parent, IDictionary serializedAdditionalRawData) - { - Version = version; - UpdatedOn = updatedOn; - UpdatedBy = updatedBy; - Parent = parent; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The version number of the object. - [WirePath("version")] - public int? Version { get; } - /// The date and time when this object was last updated. - [WirePath("updatedTime")] - public DateTimeOffset? UpdatedOn { get; } - /// The identity of the principal or process that updated the object. - [WirePath("updatedBy")] - public string UpdatedBy { get; } - /// (Optional) The ID of the parent management group used during creation. - [WirePath("parent")] - public ManagementGroupParentCreateOptions Parent { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantData.Serialization.cs deleted file mode 100644 index e9b4dc430a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantData.Serialization.cs +++ /dev/null @@ -1,318 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class DescendantData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DescendantData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (Optional.IsDefined(DisplayName)) - { - if (DisplayName != null) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - else - { - writer.WriteNull("displayName"); - } - } - if (Optional.IsDefined(Parent)) - { - if (Parent != null) - { - writer.WritePropertyName("parent"u8); - writer.WriteObjectValue(Parent, options); - } - else - { - writer.WriteNull("parent"); - } - } - writer.WriteEndObject(); - } - - DescendantData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DescendantData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDescendantData(document.RootElement, options); - } - - internal static DescendantData DeserializeDescendantData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - string displayName = default; - DescendantParentGroupInfo parent = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("displayName"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - displayName = null; - continue; - } - displayName = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("parent"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - parent = null; - continue; - } - parent = DescendantParentGroupInfo.DeserializeDescendantParentGroupInfo(property0.Value, options); - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new DescendantData( - id, - name, - type, - systemData, - displayName, - parent, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.Append(" properties:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue("ParentId", out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parent: "); - builder.AppendLine("{"); - builder.AppendLine(" parent: {"); - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - builder.AppendLine(" }"); - builder.AppendLine(" }"); - } - else - { - if (Optional.IsDefined(Parent)) - { - builder.Append(" parent: "); - BicepSerializationHelpers.AppendChildObject(builder, Parent, options, 4, false, " parent: "); - } - } - - builder.AppendLine(" }"); - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(DescendantData)} does not support writing '{options.Format}' format."); - } - } - - DescendantData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeDescendantData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DescendantData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantData.cs deleted file mode 100644 index b6d4f43ca7..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantData.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The descendant. - public partial class DescendantData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal DescendantData() - { - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The friendly name of the management group. - /// The ID of the parent management group. - /// Keeps track of any properties unknown to the library. - internal DescendantData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, string displayName, DescendantParentGroupInfo parent, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - DisplayName = displayName; - Parent = parent; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The friendly name of the management group. - [WirePath("properties.displayName")] - public string DisplayName { get; } - /// The ID of the parent management group. - internal DescendantParentGroupInfo Parent { get; } - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - [WirePath("properties.parent.id")] - public ResourceIdentifier ParentId - { - get => Parent?.Id; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantListResult.Serialization.cs deleted file mode 100644 index 6cbae7deda..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - internal partial class DescendantListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DescendantListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - DescendantListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DescendantListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDescendantListResult(document.RootElement, options); - } - - internal static DescendantListResult DeserializeDescendantListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(DescendantData.DeserializeDescendantData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new DescendantListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(DescendantListResult)} does not support writing '{options.Format}' format."); - } - } - - DescendantListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeDescendantListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DescendantListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantListResult.cs deleted file mode 100644 index df6d43351c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// Describes the result of the request to view descendants. - internal partial class DescendantListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal DescendantListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The list of descendants. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal DescendantListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The list of descendants. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantParentGroupInfo.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantParentGroupInfo.Serialization.cs deleted file mode 100644 index 86394650aa..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantParentGroupInfo.Serialization.cs +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - internal partial class DescendantParentGroupInfo : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DescendantParentGroupInfo)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - DescendantParentGroupInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DescendantParentGroupInfo)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDescendantParentGroupInfo(document.RootElement, options); - } - - internal static DescendantParentGroupInfo DeserializeDescendantParentGroupInfo(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new DescendantParentGroupInfo(id, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(DescendantParentGroupInfo)} does not support writing '{options.Format}' format."); - } - } - - DescendantParentGroupInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeDescendantParentGroupInfo(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DescendantParentGroupInfo)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantParentGroupInfo.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantParentGroupInfo.cs deleted file mode 100644 index 5dd49bf750..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantParentGroupInfo.cs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The ID of the parent management group. - internal partial class DescendantParentGroupInfo - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal DescendantParentGroupInfo() - { - } - - /// Initializes a new instance of . - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// Keeps track of any properties unknown to the library. - internal DescendantParentGroupInfo(ResourceIdentifier id, IDictionary serializedAdditionalRawData) - { - Id = id; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - [WirePath("id")] - public ResourceIdentifier Id { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityData.Serialization.cs deleted file mode 100644 index 6485645aad..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityData.Serialization.cs +++ /dev/null @@ -1,686 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class EntityData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(EntityData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (Optional.IsDefined(TenantId)) - { - if (TenantId != null) - { - writer.WritePropertyName("tenantId"u8); - writer.WriteStringValue(TenantId.Value); - } - else - { - writer.WriteNull("tenantId"); - } - } - if (Optional.IsDefined(DisplayName)) - { - if (DisplayName != null) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - else - { - writer.WriteNull("displayName"); - } - } - if (Optional.IsDefined(Parent)) - { - writer.WritePropertyName("parent"u8); - JsonSerializer.Serialize(writer, Parent); - } - if (Optional.IsDefined(Permissions)) - { - if (Permissions != null) - { - writer.WritePropertyName("permissions"u8); - writer.WriteStringValue(Permissions.Value.ToSerialString()); - } - else - { - writer.WriteNull("permissions"); - } - } - if (Optional.IsDefined(InheritedPermissions)) - { - if (InheritedPermissions != null) - { - writer.WritePropertyName("inheritedPermissions"u8); - writer.WriteStringValue(InheritedPermissions.Value.ToSerialString()); - } - else - { - writer.WriteNull("inheritedPermissions"); - } - } - if (Optional.IsDefined(NumberOfDescendants)) - { - if (NumberOfDescendants != null) - { - writer.WritePropertyName("numberOfDescendants"u8); - writer.WriteNumberValue(NumberOfDescendants.Value); - } - else - { - writer.WriteNull("numberOfDescendants"); - } - } - if (Optional.IsDefined(NumberOfChildren)) - { - if (NumberOfChildren != null) - { - writer.WritePropertyName("numberOfChildren"u8); - writer.WriteNumberValue(NumberOfChildren.Value); - } - else - { - writer.WriteNull("numberOfChildren"); - } - } - if (Optional.IsDefined(NumberOfChildGroups)) - { - if (NumberOfChildGroups != null) - { - writer.WritePropertyName("numberOfChildGroups"u8); - writer.WriteNumberValue(NumberOfChildGroups.Value); - } - else - { - writer.WriteNull("numberOfChildGroups"); - } - } - if (Optional.IsCollectionDefined(ParentDisplayNameChain)) - { - if (ParentDisplayNameChain != null) - { - writer.WritePropertyName("parentDisplayNameChain"u8); - writer.WriteStartArray(); - foreach (var item in ParentDisplayNameChain) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - else - { - writer.WriteNull("parentDisplayNameChain"); - } - } - if (Optional.IsCollectionDefined(ParentNameChain)) - { - if (ParentNameChain != null) - { - writer.WritePropertyName("parentNameChain"u8); - writer.WriteStartArray(); - foreach (var item in ParentNameChain) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - else - { - writer.WriteNull("parentNameChain"); - } - } - writer.WriteEndObject(); - } - - EntityData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(EntityData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeEntityData(document.RootElement, options); - } - - internal static EntityData DeserializeEntityData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - Guid? tenantId = default; - string displayName = default; - SubResource parent = default; - EntityPermission? permissions = default; - EntityPermission? inheritedPermissions = default; - int? numberOfDescendants = default; - int? numberOfChildren = default; - int? numberOfChildGroups = default; - IReadOnlyList parentDisplayNameChain = default; - IReadOnlyList parentNameChain = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("tenantId"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - tenantId = null; - continue; - } - tenantId = property0.Value.GetGuid(); - continue; - } - if (property0.NameEquals("displayName"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - displayName = null; - continue; - } - displayName = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("parent"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - parent = JsonSerializer.Deserialize(property0.Value.GetRawText()); - continue; - } - if (property0.NameEquals("permissions"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - permissions = null; - continue; - } - permissions = property0.Value.GetString().ToEntityPermission(); - continue; - } - if (property0.NameEquals("inheritedPermissions"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - inheritedPermissions = null; - continue; - } - inheritedPermissions = property0.Value.GetString().ToEntityPermission(); - continue; - } - if (property0.NameEquals("numberOfDescendants"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - numberOfDescendants = null; - continue; - } - numberOfDescendants = property0.Value.GetInt32(); - continue; - } - if (property0.NameEquals("numberOfChildren"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - numberOfChildren = null; - continue; - } - numberOfChildren = property0.Value.GetInt32(); - continue; - } - if (property0.NameEquals("numberOfChildGroups"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - numberOfChildGroups = null; - continue; - } - numberOfChildGroups = property0.Value.GetInt32(); - continue; - } - if (property0.NameEquals("parentDisplayNameChain"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - parentDisplayNameChain = null; - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - parentDisplayNameChain = array; - continue; - } - if (property0.NameEquals("parentNameChain"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - parentNameChain = null; - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - parentNameChain = array; - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new EntityData( - id, - name, - type, - systemData, - tenantId, - displayName, - parent, - permissions, - inheritedPermissions, - numberOfDescendants, - numberOfChildren, - numberOfChildGroups, - parentDisplayNameChain ?? new ChangeTrackingList(), - parentNameChain ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.Append(" properties:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TenantId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenantId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TenantId)) - { - builder.Append(" tenantId: "); - builder.AppendLine($"'{TenantId.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue("ParentId", out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parent: "); - builder.AppendLine("{"); - builder.AppendLine(" parent: {"); - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - builder.AppendLine(" }"); - builder.AppendLine(" }"); - } - else - { - if (Optional.IsDefined(Parent)) - { - builder.Append(" parent: "); - BicepSerializationHelpers.AppendChildObject(builder, Parent, options, 4, false, " parent: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Permissions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" permissions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Permissions)) - { - builder.Append(" permissions: "); - builder.AppendLine($"'{Permissions.Value.ToSerialString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(InheritedPermissions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" inheritedPermissions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(InheritedPermissions)) - { - builder.Append(" inheritedPermissions: "); - builder.AppendLine($"'{InheritedPermissions.Value.ToSerialString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NumberOfDescendants), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" numberOfDescendants: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NumberOfDescendants)) - { - builder.Append(" numberOfDescendants: "); - builder.AppendLine($"{NumberOfDescendants.Value}"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NumberOfChildren), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" numberOfChildren: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NumberOfChildren)) - { - builder.Append(" numberOfChildren: "); - builder.AppendLine($"{NumberOfChildren.Value}"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NumberOfChildGroups), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" numberOfChildGroups: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NumberOfChildGroups)) - { - builder.Append(" numberOfChildGroups: "); - builder.AppendLine($"{NumberOfChildGroups.Value}"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ParentDisplayNameChain), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parentDisplayNameChain: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ParentDisplayNameChain)) - { - if (ParentDisplayNameChain.Any()) - { - builder.Append(" parentDisplayNameChain: "); - builder.AppendLine("["); - foreach (var item in ParentDisplayNameChain) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ParentNameChain), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parentNameChain: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ParentNameChain)) - { - if (ParentNameChain.Any()) - { - builder.Append(" parentNameChain: "); - builder.AppendLine("["); - foreach (var item in ParentNameChain) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine(" }"); - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(EntityData)} does not support writing '{options.Format}' format."); - } - } - - EntityData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeEntityData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(EntityData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityData.cs deleted file mode 100644 index 08b09466be..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityData.cs +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The entity. - public partial class EntityData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal EntityData() - { - ParentDisplayNameChain = new ChangeTrackingList(); - ParentNameChain = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The AAD Tenant ID associated with the entity. For example, 00000000-0000-0000-0000-000000000000. - /// The friendly name of the management group. - /// (Optional) The ID of the parent management group. - /// The users specific permissions to this item. - /// The users specific permissions to this item. - /// Number of Descendants. - /// Number of children is the number of Groups and Subscriptions that are exactly one level underneath the current Group. - /// Number of children is the number of Groups that are exactly one level underneath the current Group. - /// The parent display name chain from the root group to the immediate parent. - /// The parent name chain from the root group to the immediate parent. - /// Keeps track of any properties unknown to the library. - internal EntityData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, Guid? tenantId, string displayName, SubResource parent, EntityPermission? permissions, EntityPermission? inheritedPermissions, int? numberOfDescendants, int? numberOfChildren, int? numberOfChildGroups, IReadOnlyList parentDisplayNameChain, IReadOnlyList parentNameChain, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - TenantId = tenantId; - DisplayName = displayName; - Parent = parent; - Permissions = permissions; - InheritedPermissions = inheritedPermissions; - NumberOfDescendants = numberOfDescendants; - NumberOfChildren = numberOfChildren; - NumberOfChildGroups = numberOfChildGroups; - ParentDisplayNameChain = parentDisplayNameChain; - ParentNameChain = parentNameChain; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The AAD Tenant ID associated with the entity. For example, 00000000-0000-0000-0000-000000000000. - [WirePath("properties.tenantId")] - public Guid? TenantId { get; } - /// The friendly name of the management group. - [WirePath("properties.displayName")] - public string DisplayName { get; } - /// (Optional) The ID of the parent management group. - internal SubResource Parent { get; } - /// Gets Id. - [WirePath("properties.parent.id")] - public ResourceIdentifier ParentId - { - get => Parent?.Id; - } - - /// The users specific permissions to this item. - [WirePath("properties.permissions")] - public EntityPermission? Permissions { get; } - /// The users specific permissions to this item. - [WirePath("properties.inheritedPermissions")] - public EntityPermission? InheritedPermissions { get; } - /// Number of Descendants. - [WirePath("properties.numberOfDescendants")] - public int? NumberOfDescendants { get; } - /// Number of children is the number of Groups and Subscriptions that are exactly one level underneath the current Group. - [WirePath("properties.numberOfChildren")] - public int? NumberOfChildren { get; } - /// Number of children is the number of Groups that are exactly one level underneath the current Group. - [WirePath("properties.numberOfChildGroups")] - public int? NumberOfChildGroups { get; } - /// The parent display name chain from the root group to the immediate parent. - [WirePath("properties.parentDisplayNameChain")] - public IReadOnlyList ParentDisplayNameChain { get; } - /// The parent name chain from the root group to the immediate parent. - [WirePath("properties.parentNameChain")] - public IReadOnlyList ParentNameChain { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityListResult.Serialization.cs deleted file mode 100644 index b91683219a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityListResult.Serialization.cs +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - internal partial class EntityListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(EntityListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(Count)) - { - writer.WritePropertyName("count"u8); - writer.WriteNumberValue(Count.Value); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - EntityListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(EntityListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeEntityListResult(document.RootElement, options); - } - - internal static EntityListResult DeserializeEntityListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - int? count = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(EntityData.DeserializeEntityData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("count"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - count = property.Value.GetInt32(); - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new EntityListResult(value ?? new ChangeTrackingList(), count, nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Count), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" count: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Count)) - { - builder.Append(" count: "); - builder.AppendLine($"{Count.Value}"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(EntityListResult)} does not support writing '{options.Format}' format."); - } - } - - EntityListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeEntityListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(EntityListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityListResult.cs deleted file mode 100644 index 64d4927aa3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityListResult.cs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// Describes the result of the request to view entities. - internal partial class EntityListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal EntityListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The list of entities. - /// Total count of records that match the filter. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal EntityListResult(IReadOnlyList value, int? count, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - Count = count; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The list of entities. - public IReadOnlyList Value { get; } - /// Total count of records that match the filter. - public int? Count { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityPermission.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityPermission.Serialization.cs deleted file mode 100644 index a83caa1d91..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityPermission.Serialization.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - internal static partial class EntityPermissionExtensions - { - public static string ToSerialString(this EntityPermission value) => value switch - { - EntityPermission.NoAccess => "noaccess", - EntityPermission.View => "view", - EntityPermission.Edit => "edit", - EntityPermission.Delete => "delete", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown EntityPermission value.") - }; - - public static EntityPermission ToEntityPermission(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "noaccess")) return EntityPermission.NoAccess; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "view")) return EntityPermission.View; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "edit")) return EntityPermission.Edit; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "delete")) return EntityPermission.Delete; - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown EntityPermission value."); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityPermission.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityPermission.cs deleted file mode 100644 index c7a2a6c4cb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityPermission.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The users specific permissions to this item. - public enum EntityPermission - { - /// noaccess. - NoAccess, - /// view. - View, - /// edit. - Edit, - /// delete. - Delete - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntitySearchOption.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntitySearchOption.cs deleted file mode 100644 index f4893f29e1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntitySearchOption.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The EntitySearchOption. - public readonly partial struct EntitySearchOption : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public EntitySearchOption(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string AllowedParentsValue = "AllowedParents"; - private const string AllowedChildrenValue = "AllowedChildren"; - private const string ParentAndFirstLevelChildrenValue = "ParentAndFirstLevelChildren"; - private const string ParentOnlyValue = "ParentOnly"; - private const string ChildrenOnlyValue = "ChildrenOnly"; - - /// AllowedParents. - public static EntitySearchOption AllowedParents { get; } = new EntitySearchOption(AllowedParentsValue); - /// AllowedChildren. - public static EntitySearchOption AllowedChildren { get; } = new EntitySearchOption(AllowedChildrenValue); - /// ParentAndFirstLevelChildren. - public static EntitySearchOption ParentAndFirstLevelChildren { get; } = new EntitySearchOption(ParentAndFirstLevelChildrenValue); - /// ParentOnly. - public static EntitySearchOption ParentOnly { get; } = new EntitySearchOption(ParentOnlyValue); - /// ChildrenOnly. - public static EntitySearchOption ChildrenOnly { get; } = new EntitySearchOption(ChildrenOnlyValue); - /// Determines if two values are the same. - public static bool operator ==(EntitySearchOption left, EntitySearchOption right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(EntitySearchOption left, EntitySearchOption right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator EntitySearchOption(string value) => new EntitySearchOption(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is EntitySearchOption other && Equals(other); - /// - public bool Equals(EntitySearchOption other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityViewOption.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityViewOption.cs deleted file mode 100644 index d9b563079f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityViewOption.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The EntityViewOption. - public readonly partial struct EntityViewOption : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public EntityViewOption(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string FullHierarchyValue = "FullHierarchy"; - private const string GroupsOnlyValue = "GroupsOnly"; - private const string SubscriptionsOnlyValue = "SubscriptionsOnly"; - private const string AuditValue = "Audit"; - - /// FullHierarchy. - public static EntityViewOption FullHierarchy { get; } = new EntityViewOption(FullHierarchyValue); - /// GroupsOnly. - public static EntityViewOption GroupsOnly { get; } = new EntityViewOption(GroupsOnlyValue); - /// SubscriptionsOnly. - public static EntityViewOption SubscriptionsOnly { get; } = new EntityViewOption(SubscriptionsOnlyValue); - /// Audit. - public static EntityViewOption Audit { get; } = new EntityViewOption(AuditValue); - /// Determines if two values are the same. - public static bool operator ==(EntityViewOption left, EntityViewOption right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(EntityViewOption left, EntityViewOption right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator EntityViewOption(string value) => new EntityViewOption(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is EntityViewOption other && Equals(other); - /// - public bool Equals(EntityViewOption other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.Serialization.cs deleted file mode 100644 index d11c5c97e0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - internal partial class ListSubscriptionUnderManagementGroup : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ListSubscriptionUnderManagementGroup)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ListSubscriptionUnderManagementGroup IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ListSubscriptionUnderManagementGroup)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeListSubscriptionUnderManagementGroup(document.RootElement, options); - } - - internal static ListSubscriptionUnderManagementGroup DeserializeListSubscriptionUnderManagementGroup(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ManagementGroupSubscriptionData.DeserializeManagementGroupSubscriptionData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ListSubscriptionUnderManagementGroup(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ListSubscriptionUnderManagementGroup)} does not support writing '{options.Format}' format."); - } - } - - ListSubscriptionUnderManagementGroup IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeListSubscriptionUnderManagementGroup(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ListSubscriptionUnderManagementGroup)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.cs deleted file mode 100644 index 2b3b56a128..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The details of all subscriptions under management group. - internal partial class ListSubscriptionUnderManagementGroup - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ListSubscriptionUnderManagementGroup() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The list of subscriptions. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal ListSubscriptionUnderManagementGroup(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The list of subscriptions. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildInfo.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildInfo.Serialization.cs deleted file mode 100644 index bf90302465..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildInfo.Serialization.cs +++ /dev/null @@ -1,308 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupChildInfo : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupChildInfo)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(ChildType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ChildType.Value.ToString()); - } - if (Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (Optional.IsCollectionDefined(Children)) - { - writer.WritePropertyName("children"u8); - writer.WriteStartArray(); - foreach (var item in Children) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ManagementGroupChildInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupChildInfo)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupChildInfo(document.RootElement, options); - } - - internal static ManagementGroupChildInfo DeserializeManagementGroupChildInfo(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ManagementGroupChildType? type = default; - string id = default; - string name = default; - string displayName = default; - IReadOnlyList children = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = new ManagementGroupChildType(property.Value.GetString()); - continue; - } - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (property.NameEquals("children"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(DeserializeManagementGroupChildInfo(item, options)); - } - children = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupChildInfo( - type, - id, - name, - displayName, - children ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - if (Id.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Id}'''"); - } - else - { - builder.AppendLine($"'{Id}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Children), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" children: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Children)) - { - if (Children.Any()) - { - builder.Append(" children: "); - builder.AppendLine("["); - foreach (var item in Children) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " children: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementGroupChildInfo)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupChildInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupChildInfo(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupChildInfo)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildInfo.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildInfo.cs deleted file mode 100644 index 57e19925e0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildInfo.cs +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The child information of a management group. - public partial class ManagementGroupChildInfo - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagementGroupChildInfo() - { - Children = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The fully qualified resource type which includes provider namespace (e.g. Microsoft.Management/managementGroups). - /// The fully qualified ID for the child resource (management group or subscription). For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The name of the child entity. - /// The friendly name of the child resource. - /// The list of children. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupChildInfo(ManagementGroupChildType? childType, string id, string name, string displayName, IReadOnlyList children, IDictionary serializedAdditionalRawData) - { - ChildType = childType; - Id = id; - Name = name; - DisplayName = displayName; - Children = children; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The fully qualified resource type which includes provider namespace (e.g. Microsoft.Management/managementGroups). - [WirePath("type")] - public ManagementGroupChildType? ChildType { get; } - /// The fully qualified ID for the child resource (management group or subscription). For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - [WirePath("id")] - public string Id { get; } - /// The name of the child entity. - [WirePath("name")] - public string Name { get; } - /// The friendly name of the child resource. - [WirePath("displayName")] - public string DisplayName { get; } - /// The list of children. - [WirePath("children")] - public IReadOnlyList Children { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildOptions.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildOptions.Serialization.cs deleted file mode 100644 index c9d1017ba4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildOptions.Serialization.cs +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupChildOptions : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupChildOptions)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(ChildType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ChildType.Value.ToString()); - } - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (options.Format != "W" && Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (options.Format != "W" && Optional.IsCollectionDefined(Children)) - { - writer.WritePropertyName("children"u8); - writer.WriteStartArray(); - foreach (var item in Children) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ManagementGroupChildOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupChildOptions)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupChildOptions(document.RootElement, options); - } - - internal static ManagementGroupChildOptions DeserializeManagementGroupChildOptions(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ManagementGroupChildType? type = default; - string id = default; - string name = default; - string displayName = default; - IReadOnlyList children = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = new ManagementGroupChildType(property.Value.GetString()); - continue; - } - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (property.NameEquals("children"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(DeserializeManagementGroupChildOptions(item, options)); - } - children = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupChildOptions( - type, - id, - name, - displayName, - children ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ManagementGroupChildOptions)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupChildOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupChildOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupChildOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildOptions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildOptions.cs deleted file mode 100644 index fa5796a8fe..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildOptions.cs +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The child information of a management group used during creation. - public partial class ManagementGroupChildOptions - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagementGroupChildOptions() - { - Children = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The fully qualified resource type which includes provider namespace (e.g. Microsoft.Management/managementGroups). - /// The fully qualified ID for the child resource (management group or subscription). For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The name of the child entity. - /// The friendly name of the child resource. - /// The list of children. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupChildOptions(ManagementGroupChildType? childType, string id, string name, string displayName, IReadOnlyList children, IDictionary serializedAdditionalRawData) - { - ChildType = childType; - Id = id; - Name = name; - DisplayName = displayName; - Children = children; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The fully qualified resource type which includes provider namespace (e.g. Microsoft.Management/managementGroups). - [WirePath("type")] - public ManagementGroupChildType? ChildType { get; } - /// The fully qualified ID for the child resource (management group or subscription). For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - [WirePath("id")] - public string Id { get; } - /// The name of the child entity. - [WirePath("name")] - public string Name { get; } - /// The friendly name of the child resource. - [WirePath("displayName")] - public string DisplayName { get; } - /// The list of children. - [WirePath("children")] - public IReadOnlyList Children { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildType.cs deleted file mode 100644 index 75e6a37c4a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildType.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The type of child resource. - public readonly partial struct ManagementGroupChildType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ManagementGroupChildType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string MicrosoftManagementManagementGroupsValue = "Microsoft.Management/managementGroups"; - private const string SubscriptionsValue = "/subscriptions"; - - /// Microsoft.Management/managementGroups. - public static ManagementGroupChildType MicrosoftManagementManagementGroups { get; } = new ManagementGroupChildType(MicrosoftManagementManagementGroupsValue); - /// /subscriptions. - public static ManagementGroupChildType Subscriptions { get; } = new ManagementGroupChildType(SubscriptionsValue); - /// Determines if two values are the same. - public static bool operator ==(ManagementGroupChildType left, ManagementGroupChildType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ManagementGroupChildType left, ManagementGroupChildType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ManagementGroupChildType(string value) => new ManagementGroupChildType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ManagementGroupChildType other && Equals(other); - /// - public bool Equals(ManagementGroupChildType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCollectionGetEntitiesOptions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCollectionGetEntitiesOptions.cs deleted file mode 100644 index 3fc2633c8a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCollectionGetEntitiesOptions.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The ManagementGroupCollectionGetEntitiesOptions. - public partial class ManagementGroupCollectionGetEntitiesOptions - { - /// Initializes a new instance of . - public ManagementGroupCollectionGetEntitiesOptions() - { - } - - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - [WirePath("skipToken")] - public string SkipToken { get; set; } - /// Number of entities to skip over when retrieving results. Passing this in will override $skipToken. - [WirePath("skip")] - public int? Skip { get; set; } - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - [WirePath("top")] - public int? Top { get; set; } - /// This parameter specifies the fields to include in the response. Can include any combination of Name,DisplayName,Type,ParentDisplayNameChain,ParentChain, e.g. '$select=Name,DisplayName,Type,ParentDisplayNameChain,ParentNameChain'. When specified the $select parameter can override select in $skipToken. - [WirePath("select")] - public string Select { get; set; } - /// - /// The $search parameter is used in conjunction with the $filter parameter to return three different outputs depending on the parameter passed in. - /// With $search=AllowedParents the API will return the entity info of all groups that the requested entity will be able to reparent to as determined by the user's permissions. - /// With $search=AllowedChildren the API will return the entity info of all entities that can be added as children of the requested entity. - /// With $search=ParentAndFirstLevelChildren the API will return the parent and first level of children that the user has either direct access to or indirect access via one of their descendants. - /// With $search=ParentOnly the API will return only the group if the user has access to at least one of the descendants of the group. - /// With $search=ChildrenOnly the API will return only the first level of children of the group entity info specified in $filter. The user must have direct access to the children entities or one of it's descendants for it to show up in the results. - /// - [WirePath("search")] - public EntitySearchOption? Search { get; set; } - /// The filter parameter allows you to filter on the the name or display name fields. You can check for equality on the name field (e.g. name eq '{entityName}') and you can check for substrings on either the name or display name fields(e.g. contains(name, '{substringToSearch}'), contains(displayName, '{substringToSearch')). Note that the '{entityName}' and '{substringToSearch}' fields are checked case insensitively. - [WirePath("filter")] - public string Filter { get; set; } - /// The view parameter allows clients to filter the type of data that is returned by the getEntities call. - [WirePath("view")] - public EntityViewOption? View { get; set; } - /// A filter which allows the get entities call to focus on a particular group (i.e. "$filter=name eq 'groupName'"). - [WirePath("groupName")] - public string GroupName { get; set; } - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - [WirePath("cacheControl")] - public string CacheControl { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.Serialization.cs deleted file mode 100644 index dcbc54534e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.Serialization.cs +++ /dev/null @@ -1,264 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupCreateOrUpdateContent : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupCreateOrUpdateContent)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && Optional.IsDefined(ResourceType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ResourceType.Value); - } - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (options.Format != "W" && Optional.IsDefined(TenantId)) - { - writer.WritePropertyName("tenantId"u8); - writer.WriteStringValue(TenantId.Value); - } - if (Optional.IsDefined(DisplayName)) - { - if (DisplayName != null) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - else - { - writer.WriteNull("displayName"); - } - } - if (Optional.IsDefined(Details)) - { - writer.WritePropertyName("details"u8); - writer.WriteObjectValue(Details, options); - } - if (options.Format != "W" && Optional.IsCollectionDefined(Children)) - { - if (Children != null) - { - writer.WritePropertyName("children"u8); - writer.WriteStartArray(); - foreach (var item in Children) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - else - { - writer.WriteNull("children"); - } - } - writer.WriteEndObject(); - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ManagementGroupCreateOrUpdateContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupCreateOrUpdateContent)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupCreateOrUpdateContent(document.RootElement, options); - } - - internal static ManagementGroupCreateOrUpdateContent DeserializeManagementGroupCreateOrUpdateContent(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string id = default; - ResourceType? type = default; - string name = default; - Guid? tenantId = default; - string displayName = default; - CreateManagementGroupDetails details = default; - IReadOnlyList children = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("tenantId"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - tenantId = property0.Value.GetGuid(); - continue; - } - if (property0.NameEquals("displayName"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - displayName = null; - continue; - } - displayName = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("details"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - details = CreateManagementGroupDetails.DeserializeCreateManagementGroupDetails(property0.Value, options); - continue; - } - if (property0.NameEquals("children"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - children = null; - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(ManagementGroupChildOptions.DeserializeManagementGroupChildOptions(item, options)); - } - children = array; - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupCreateOrUpdateContent( - id, - type, - name, - tenantId, - displayName, - details, - children ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ManagementGroupCreateOrUpdateContent)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupCreateOrUpdateContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupCreateOrUpdateContent(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupCreateOrUpdateContent)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.cs deleted file mode 100644 index 079151fec3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.cs +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// Management group creation parameters. - public partial class ManagementGroupCreateOrUpdateContent - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ManagementGroupCreateOrUpdateContent() - { - Children = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The type of the resource. For example, Microsoft.Management/managementGroups. - /// The name of the management group. For example, 00000000-0000-0000-0000-000000000000. - /// The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000. - /// The friendly name of the management group. If no value is passed then this field will be set to the groupId. - /// The details of a management group used during creation. - /// The list of children. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupCreateOrUpdateContent(string id, ResourceType? resourceType, string name, Guid? tenantId, string displayName, CreateManagementGroupDetails details, IReadOnlyList children, IDictionary serializedAdditionalRawData) - { - Id = id; - ResourceType = resourceType; - Name = name; - TenantId = tenantId; - DisplayName = displayName; - Details = details; - Children = children; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - [WirePath("id")] - public string Id { get; } - /// The type of the resource. For example, Microsoft.Management/managementGroups. - [WirePath("type")] - public ResourceType? ResourceType { get; } - /// The name of the management group. For example, 00000000-0000-0000-0000-000000000000. - [WirePath("name")] - public string Name { get; set; } - /// The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000. - [WirePath("properties.tenantId")] - public Guid? TenantId { get; } - /// The friendly name of the management group. If no value is passed then this field will be set to the groupId. - [WirePath("properties.displayName")] - public string DisplayName { get; set; } - /// The details of a management group used during creation. - [WirePath("properties.details")] - public CreateManagementGroupDetails Details { get; set; } - /// The list of children. - [WirePath("properties.children")] - public IReadOnlyList Children { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupExpandType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupExpandType.cs deleted file mode 100644 index 6fd33fdd70..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupExpandType.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The ManagementGroupExpandType. - public readonly partial struct ManagementGroupExpandType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ManagementGroupExpandType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string ChildrenValue = "children"; - private const string PathValue = "path"; - private const string AncestorsValue = "ancestors"; - - /// children. - public static ManagementGroupExpandType Children { get; } = new ManagementGroupExpandType(ChildrenValue); - /// path. - public static ManagementGroupExpandType Path { get; } = new ManagementGroupExpandType(PathValue); - /// ancestors. - public static ManagementGroupExpandType Ancestors { get; } = new ManagementGroupExpandType(AncestorsValue); - /// Determines if two values are the same. - public static bool operator ==(ManagementGroupExpandType left, ManagementGroupExpandType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ManagementGroupExpandType left, ManagementGroupExpandType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ManagementGroupExpandType(string value) => new ManagementGroupExpandType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ManagementGroupExpandType other && Equals(other); - /// - public bool Equals(ManagementGroupExpandType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupInfo.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupInfo.Serialization.cs deleted file mode 100644 index 497c65bc34..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupInfo.Serialization.cs +++ /dev/null @@ -1,451 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupInfo : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupInfo)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Version)) - { - writer.WritePropertyName("version"u8); - writer.WriteNumberValue(Version.Value); - } - if (Optional.IsDefined(UpdatedOn)) - { - writer.WritePropertyName("updatedTime"u8); - writer.WriteStringValue(UpdatedOn.Value, "O"); - } - if (Optional.IsDefined(UpdatedBy)) - { - writer.WritePropertyName("updatedBy"u8); - writer.WriteStringValue(UpdatedBy); - } - if (Optional.IsDefined(Parent)) - { - writer.WritePropertyName("parent"u8); - writer.WriteObjectValue(Parent, options); - } - if (Optional.IsCollectionDefined(Path)) - { - if (Path != null) - { - writer.WritePropertyName("path"u8); - writer.WriteStartArray(); - foreach (var item in Path) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - else - { - writer.WriteNull("path"); - } - } - if (Optional.IsCollectionDefined(ManagementGroupAncestors)) - { - if (ManagementGroupAncestors != null) - { - writer.WritePropertyName("managementGroupAncestors"u8); - writer.WriteStartArray(); - foreach (var item in ManagementGroupAncestors) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - else - { - writer.WriteNull("managementGroupAncestors"); - } - } - if (Optional.IsCollectionDefined(ManagementGroupAncestorChain)) - { - if (ManagementGroupAncestorChain != null) - { - writer.WritePropertyName("managementGroupAncestorsChain"u8); - writer.WriteStartArray(); - foreach (var item in ManagementGroupAncestorChain) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - else - { - writer.WriteNull("managementGroupAncestorsChain"); - } - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ManagementGroupInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupInfo)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupInfo(document.RootElement, options); - } - - internal static ManagementGroupInfo DeserializeManagementGroupInfo(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - int? version = default; - DateTimeOffset? updatedTime = default; - string updatedBy = default; - ParentManagementGroupInfo parent = default; - IReadOnlyList path = default; - IReadOnlyList managementGroupAncestors = default; - IReadOnlyList managementGroupAncestorsChain = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("version"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - version = property.Value.GetInt32(); - continue; - } - if (property.NameEquals("updatedTime"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - updatedTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("updatedBy"u8)) - { - updatedBy = property.Value.GetString(); - continue; - } - if (property.NameEquals("parent"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - parent = ParentManagementGroupInfo.DeserializeParentManagementGroupInfo(property.Value, options); - continue; - } - if (property.NameEquals("path"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - path = null; - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ManagementGroupPathElement.DeserializeManagementGroupPathElement(item, options)); - } - path = array; - continue; - } - if (property.NameEquals("managementGroupAncestors"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - managementGroupAncestors = null; - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - managementGroupAncestors = array; - continue; - } - if (property.NameEquals("managementGroupAncestorsChain"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - managementGroupAncestorsChain = null; - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ManagementGroupPathElement.DeserializeManagementGroupPathElement(item, options)); - } - managementGroupAncestorsChain = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupInfo( - version, - updatedTime, - updatedBy, - parent, - path ?? new ChangeTrackingList(), - managementGroupAncestors ?? new ChangeTrackingList(), - managementGroupAncestorsChain ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Version), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" version: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Version)) - { - builder.Append(" version: "); - builder.AppendLine($"{Version.Value}"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(UpdatedOn), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" updatedTime: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(UpdatedOn)) - { - builder.Append(" updatedTime: "); - var formattedDateTimeString = TypeFormatters.ToString(UpdatedOn.Value, "o"); - builder.AppendLine($"'{formattedDateTimeString}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(UpdatedBy), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" updatedBy: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(UpdatedBy)) - { - builder.Append(" updatedBy: "); - if (UpdatedBy.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{UpdatedBy}'''"); - } - else - { - builder.AppendLine($"'{UpdatedBy}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Parent), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parent: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Parent)) - { - builder.Append(" parent: "); - BicepSerializationHelpers.AppendChildObject(builder, Parent, options, 2, false, " parent: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Path), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" path: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Path)) - { - if (Path.Any()) - { - builder.Append(" path: "); - builder.AppendLine("["); - foreach (var item in Path) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " path: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ManagementGroupAncestors), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" managementGroupAncestors: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ManagementGroupAncestors)) - { - if (ManagementGroupAncestors.Any()) - { - builder.Append(" managementGroupAncestors: "); - builder.AppendLine("["); - foreach (var item in ManagementGroupAncestors) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ManagementGroupAncestorChain), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" managementGroupAncestorsChain: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ManagementGroupAncestorChain)) - { - if (ManagementGroupAncestorChain.Any()) - { - builder.Append(" managementGroupAncestorsChain: "); - builder.AppendLine("["); - foreach (var item in ManagementGroupAncestorChain) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " managementGroupAncestorsChain: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementGroupInfo)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupInfo(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupInfo)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupInfo.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupInfo.cs deleted file mode 100644 index 05985dbcf7..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupInfo.cs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// The details of a management group. - public partial class ManagementGroupInfo - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagementGroupInfo() - { - Path = new ChangeTrackingList(); - ManagementGroupAncestors = new ChangeTrackingList(); - ManagementGroupAncestorChain = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The version number of the object. - /// The date and time when this object was last updated. - /// The identity of the principal or process that updated the object. - /// (Optional) The ID of the parent management group. - /// The path from the root to the current group. - /// The ancestors of the management group. - /// The ancestors of the management group displayed in reversed order, from immediate parent to the root. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupInfo(int? version, DateTimeOffset? updatedOn, string updatedBy, ParentManagementGroupInfo parent, IReadOnlyList path, IReadOnlyList managementGroupAncestors, IReadOnlyList managementGroupAncestorChain, IDictionary serializedAdditionalRawData) - { - Version = version; - UpdatedOn = updatedOn; - UpdatedBy = updatedBy; - Parent = parent; - Path = path; - ManagementGroupAncestors = managementGroupAncestors; - ManagementGroupAncestorChain = managementGroupAncestorChain; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The version number of the object. - [WirePath("version")] - public int? Version { get; } - /// The date and time when this object was last updated. - [WirePath("updatedTime")] - public DateTimeOffset? UpdatedOn { get; } - /// The identity of the principal or process that updated the object. - [WirePath("updatedBy")] - public string UpdatedBy { get; } - /// (Optional) The ID of the parent management group. - [WirePath("parent")] - public ParentManagementGroupInfo Parent { get; } - /// The path from the root to the current group. - [WirePath("path")] - public IReadOnlyList Path { get; } - /// The ancestors of the management group. - [WirePath("managementGroupAncestors")] - public IReadOnlyList ManagementGroupAncestors { get; } - /// The ancestors of the management group displayed in reversed order, from immediate parent to the root. - [WirePath("managementGroupAncestorsChain")] - public IReadOnlyList ManagementGroupAncestorChain { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupListResult.Serialization.cs deleted file mode 100644 index 3d7f50a501..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - internal partial class ManagementGroupListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("@nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ManagementGroupListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupListResult(document.RootElement, options); - } - - internal static ManagementGroupListResult DeserializeManagementGroupListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ManagementGroupData.DeserializeManagementGroupData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("@nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" @nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" @nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementGroupListResult)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupListResult.cs deleted file mode 100644 index 814cf13d89..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// Describes the result of the request to list management groups. - internal partial class ManagementGroupListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagementGroupListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The list of management groups. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The list of management groups. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.Serialization.cs deleted file mode 100644 index f986e9f7ba..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.Serialization.cs +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupNameAvailabilityContent : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupNameAvailabilityContent)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(ResourceType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ResourceType.Value); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ManagementGroupNameAvailabilityContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupNameAvailabilityContent)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupNameAvailabilityContent(document.RootElement, options); - } - - internal static ManagementGroupNameAvailabilityContent DeserializeManagementGroupNameAvailabilityContent(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - ResourceType? type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = new ResourceType(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupNameAvailabilityContent(name, type, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ManagementGroupNameAvailabilityContent)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupNameAvailabilityContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupNameAvailabilityContent(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupNameAvailabilityContent)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.cs deleted file mode 100644 index cbe681771f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.cs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// Management group name availability check parameters. - public partial class ManagementGroupNameAvailabilityContent - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// the name to check for availability. - /// fully qualified resource type which includes provider namespace. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupNameAvailabilityContent(string name, ResourceType? resourceType, IDictionary serializedAdditionalRawData) - { - Name = name; - ResourceType = resourceType; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// the name to check for availability. - [WirePath("name")] - public string Name { get; set; } - /// fully qualified resource type which includes provider namespace. - [WirePath("type")] - public ResourceType? ResourceType { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.Serialization.cs deleted file mode 100644 index bde0af8255..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.Serialization.cs +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupNameAvailabilityResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupNameAvailabilityResult)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(NameAvailable)) - { - writer.WritePropertyName("nameAvailable"u8); - writer.WriteBooleanValue(NameAvailable.Value); - } - if (options.Format != "W" && Optional.IsDefined(Reason)) - { - writer.WritePropertyName("reason"u8); - writer.WriteStringValue(Reason.Value.ToSerialString()); - } - if (options.Format != "W" && Optional.IsDefined(Message)) - { - writer.WritePropertyName("message"u8); - writer.WriteStringValue(Message); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ManagementGroupNameAvailabilityResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupNameAvailabilityResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupNameAvailabilityResult(document.RootElement, options); - } - - internal static ManagementGroupNameAvailabilityResult DeserializeManagementGroupNameAvailabilityResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - bool? nameAvailable = default; - ManagementGroupNameUnavailableReason? reason = default; - string message = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("nameAvailable"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - nameAvailable = property.Value.GetBoolean(); - continue; - } - if (property.NameEquals("reason"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - reason = property.Value.GetString().ToManagementGroupNameUnavailableReason(); - continue; - } - if (property.NameEquals("message"u8)) - { - message = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupNameAvailabilityResult(nameAvailable, reason, message, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NameAvailable), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nameAvailable: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NameAvailable)) - { - builder.Append(" nameAvailable: "); - var boolValue = NameAvailable.Value == true ? "true" : "false"; - builder.AppendLine($"{boolValue}"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Reason), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" reason: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Reason)) - { - builder.Append(" reason: "); - builder.AppendLine($"'{Reason.Value.ToSerialString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Message), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" message: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Message)) - { - builder.Append(" message: "); - if (Message.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Message}'''"); - } - else - { - builder.AppendLine($"'{Message}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementGroupNameAvailabilityResult)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupNameAvailabilityResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupNameAvailabilityResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupNameAvailabilityResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.cs deleted file mode 100644 index 1c2a592629..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// Describes the result of the request to check management group name availability. - public partial class ManagementGroupNameAvailabilityResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagementGroupNameAvailabilityResult() - { - } - - /// Initializes a new instance of . - /// Required. True indicates name is valid and available. False indicates the name is invalid, unavailable, or both. - /// Required if nameAvailable == false. Invalid indicates the name provided does not match the resource provider's naming requirements (incorrect length, unsupported characters, etc.) AlreadyExists indicates that the name is already in use and is therefore unavailable. - /// Required if nameAvailable == false. Localized. If reason == invalid, provide the user with the reason why the given name is invalid, and provide the resource naming requirements so that the user can select a valid name. If reason == AlreadyExists, explain that is already in use, and direct them to select a different name. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupNameAvailabilityResult(bool? nameAvailable, ManagementGroupNameUnavailableReason? reason, string message, IDictionary serializedAdditionalRawData) - { - NameAvailable = nameAvailable; - Reason = reason; - Message = message; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Required. True indicates name is valid and available. False indicates the name is invalid, unavailable, or both. - [WirePath("nameAvailable")] - public bool? NameAvailable { get; } - /// Required if nameAvailable == false. Invalid indicates the name provided does not match the resource provider's naming requirements (incorrect length, unsupported characters, etc.) AlreadyExists indicates that the name is already in use and is therefore unavailable. - [WirePath("reason")] - public ManagementGroupNameUnavailableReason? Reason { get; } - /// Required if nameAvailable == false. Localized. If reason == invalid, provide the user with the reason why the given name is invalid, and provide the resource naming requirements so that the user can select a valid name. If reason == AlreadyExists, explain that is already in use, and direct them to select a different name. - [WirePath("message")] - public string Message { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.Serialization.cs deleted file mode 100644 index 682fa73fb9..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.Serialization.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - internal static partial class ManagementGroupNameUnavailableReasonExtensions - { - public static string ToSerialString(this ManagementGroupNameUnavailableReason value) => value switch - { - ManagementGroupNameUnavailableReason.Invalid => "Invalid", - ManagementGroupNameUnavailableReason.AlreadyExists => "AlreadyExists", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ManagementGroupNameUnavailableReason value.") - }; - - public static ManagementGroupNameUnavailableReason ToManagementGroupNameUnavailableReason(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Invalid")) return ManagementGroupNameUnavailableReason.Invalid; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "AlreadyExists")) return ManagementGroupNameUnavailableReason.AlreadyExists; - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ManagementGroupNameUnavailableReason value."); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.cs deleted file mode 100644 index 71cedf1e26..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// Required if nameAvailable == false. Invalid indicates the name provided does not match the resource provider's naming requirements (incorrect length, unsupported characters, etc.) AlreadyExists indicates that the name is already in use and is therefore unavailable. - public enum ManagementGroupNameUnavailableReason - { - /// Invalid. - Invalid, - /// AlreadyExists. - AlreadyExists - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.Serialization.cs deleted file mode 100644 index 7210e1adcc..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.Serialization.cs +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupParentCreateOptions : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupParentCreateOptions)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (options.Format != "W" && Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ManagementGroupParentCreateOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupParentCreateOptions)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupParentCreateOptions(document.RootElement, options); - } - - internal static ManagementGroupParentCreateOptions DeserializeManagementGroupParentCreateOptions(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string id = default; - string name = default; - string displayName = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupParentCreateOptions(id, name, displayName, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ManagementGroupParentCreateOptions)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupParentCreateOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupParentCreateOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupParentCreateOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.cs deleted file mode 100644 index 13e65d6bf7..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// (Optional) The ID of the parent management group used during creation. - public partial class ManagementGroupParentCreateOptions - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ManagementGroupParentCreateOptions() - { - } - - /// Initializes a new instance of . - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The name of the parent management group. - /// The friendly name of the parent management group. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupParentCreateOptions(string id, string name, string displayName, IDictionary serializedAdditionalRawData) - { - Id = id; - Name = name; - DisplayName = displayName; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - [WirePath("id")] - public string Id { get; set; } - /// The name of the parent management group. - [WirePath("name")] - public string Name { get; } - /// The friendly name of the parent management group. - [WirePath("displayName")] - public string DisplayName { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPatch.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPatch.Serialization.cs deleted file mode 100644 index 7b047c7af2..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPatch.Serialization.cs +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupPatch : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupPatch)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(DisplayName)) - { - if (DisplayName != null) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - else - { - writer.WriteNull("displayName"); - } - } - if (Optional.IsDefined(ParentGroupId)) - { - if (ParentGroupId != null) - { - writer.WritePropertyName("parentGroupId"u8); - writer.WriteStringValue(ParentGroupId); - } - else - { - writer.WriteNull("parentGroupId"); - } - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ManagementGroupPatch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupPatch)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupPatch(document.RootElement, options); - } - - internal static ManagementGroupPatch DeserializeManagementGroupPatch(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string displayName = default; - string parentGroupId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("displayName"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - displayName = null; - continue; - } - displayName = property.Value.GetString(); - continue; - } - if (property.NameEquals("parentGroupId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - parentGroupId = null; - continue; - } - parentGroupId = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupPatch(displayName, parentGroupId, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ManagementGroupPatch)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupPatch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupPatch(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupPatch)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPatch.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPatch.cs deleted file mode 100644 index 8d3aeabcf3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPatch.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// Management group patch parameters. - public partial class ManagementGroupPatch - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ManagementGroupPatch() - { - } - - /// Initializes a new instance of . - /// The friendly name of the management group. - /// (Optional) The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupPatch(string displayName, string parentGroupId, IDictionary serializedAdditionalRawData) - { - DisplayName = displayName; - ParentGroupId = parentGroupId; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The friendly name of the management group. - [WirePath("displayName")] - public string DisplayName { get; set; } - /// (Optional) The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - [WirePath("parentGroupId")] - public string ParentGroupId { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPathElement.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPathElement.Serialization.cs deleted file mode 100644 index d1c5dae155..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPathElement.Serialization.cs +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ManagementGroupPathElement : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupPathElement)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ManagementGroupPathElement IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementGroupPathElement)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementGroupPathElement(document.RootElement, options); - } - - internal static ManagementGroupPathElement DeserializeManagementGroupPathElement(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - string displayName = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementGroupPathElement(name, displayName, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementGroupPathElement)} does not support writing '{options.Format}' format."); - } - } - - ManagementGroupPathElement IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementGroupPathElement(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementGroupPathElement)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPathElement.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPathElement.cs deleted file mode 100644 index 83a547b41a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPathElement.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// A path element of a management group ancestors. - public partial class ManagementGroupPathElement - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagementGroupPathElement() - { - } - - /// Initializes a new instance of . - /// The name of the group. - /// The friendly name of the group. - /// Keeps track of any properties unknown to the library. - internal ManagementGroupPathElement(string name, string displayName, IDictionary serializedAdditionalRawData) - { - Name = name; - DisplayName = displayName; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The name of the group. - [WirePath("name")] - public string Name { get; } - /// The friendly name of the group. - [WirePath("displayName")] - public string DisplayName { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ParentManagementGroupInfo.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ParentManagementGroupInfo.Serialization.cs deleted file mode 100644 index 9cc8ebf326..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ParentManagementGroupInfo.Serialization.cs +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - public partial class ParentManagementGroupInfo : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ParentManagementGroupInfo)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ParentManagementGroupInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ParentManagementGroupInfo)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeParentManagementGroupInfo(document.RootElement, options); - } - - internal static ParentManagementGroupInfo DeserializeParentManagementGroupInfo(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string id = default; - string name = default; - string displayName = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ParentManagementGroupInfo(id, name, displayName, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - if (Id.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Id}'''"); - } - else - { - builder.AppendLine($"'{Id}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ParentManagementGroupInfo)} does not support writing '{options.Format}' format."); - } - } - - ParentManagementGroupInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeParentManagementGroupInfo(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ParentManagementGroupInfo)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ParentManagementGroupInfo.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ParentManagementGroupInfo.cs deleted file mode 100644 index 910a28524a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ParentManagementGroupInfo.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.ManagementGroups.Models -{ - /// (Optional) The ID of the parent management group. - public partial class ParentManagementGroupInfo - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ParentManagementGroupInfo() - { - } - - /// Initializes a new instance of . - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The name of the parent management group. - /// The friendly name of the parent management group. - /// Keeps track of any properties unknown to the library. - internal ParentManagementGroupInfo(string id, string name, string displayName, IDictionary serializedAdditionalRawData) - { - Id = id; - Name = name; - DisplayName = displayName; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - [WirePath("id")] - public string Id { get; } - /// The name of the parent management group. - [WirePath("name")] - public string Name { get; } - /// The friendly name of the parent management group. - [WirePath("displayName")] - public string DisplayName { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ResourceManagerModelFactory.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ResourceManagerModelFactory.cs deleted file mode 100644 index 71c0f3315e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/ResourceManagerModelFactory.cs +++ /dev/null @@ -1,269 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Linq; -using Azure.Core; -using Azure.ResourceManager.ManagementGroups; -using Azure.ResourceManager.ManagementGroups.Models; - -namespace Azure.ResourceManager.Models -{ - /// Model factory for models. - public static partial class ResourceManagerModelFactory - { - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000. - /// The friendly name of the management group. - /// The details of a management group. - /// The list of children. - /// A new instance for mocking. - public static ManagementGroupData ManagementGroupData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, Guid? tenantId = null, string displayName = null, ManagementGroupInfo details = null, IEnumerable children = null) - { - children ??= new List(); - - return new ManagementGroupData( - id, - name, - resourceType, - systemData, - tenantId, - displayName, - details, - children?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The version number of the object. - /// The date and time when this object was last updated. - /// The identity of the principal or process that updated the object. - /// (Optional) The ID of the parent management group. - /// The path from the root to the current group. - /// The ancestors of the management group. - /// The ancestors of the management group displayed in reversed order, from immediate parent to the root. - /// A new instance for mocking. - public static ManagementGroupInfo ManagementGroupInfo(int? version = null, DateTimeOffset? updatedOn = null, string updatedBy = null, ParentManagementGroupInfo parent = null, IEnumerable path = null, IEnumerable managementGroupAncestors = null, IEnumerable managementGroupAncestorChain = null) - { - path ??= new List(); - managementGroupAncestors ??= new List(); - managementGroupAncestorChain ??= new List(); - - return new ManagementGroupInfo( - version, - updatedOn, - updatedBy, - parent, - path?.ToList(), - managementGroupAncestors?.ToList(), - managementGroupAncestorChain?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The name of the parent management group. - /// The friendly name of the parent management group. - /// A new instance for mocking. - public static ParentManagementGroupInfo ParentManagementGroupInfo(string id = null, string name = null, string displayName = null) - { - return new ParentManagementGroupInfo(id, name, displayName, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The name of the group. - /// The friendly name of the group. - /// A new instance for mocking. - public static ManagementGroupPathElement ManagementGroupPathElement(string name = null, string displayName = null) - { - return new ManagementGroupPathElement(name, displayName, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The fully qualified resource type which includes provider namespace (e.g. Microsoft.Management/managementGroups). - /// The fully qualified ID for the child resource (management group or subscription). For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The name of the child entity. - /// The friendly name of the child resource. - /// The list of children. - /// A new instance for mocking. - public static ManagementGroupChildInfo ManagementGroupChildInfo(ManagementGroupChildType? childType = null, string id = null, string name = null, string displayName = null, IEnumerable children = null) - { - children ??= new List(); - - return new ManagementGroupChildInfo( - childType, - id, - name, - displayName, - children?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The type of the resource. For example, Microsoft.Management/managementGroups. - /// The name of the management group. For example, 00000000-0000-0000-0000-000000000000. - /// The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000. - /// The friendly name of the management group. If no value is passed then this field will be set to the groupId. - /// The details of a management group used during creation. - /// The list of children. - /// A new instance for mocking. - public static ManagementGroupCreateOrUpdateContent ManagementGroupCreateOrUpdateContent(string id = null, ResourceType? resourceType = null, string name = null, Guid? tenantId = null, string displayName = null, CreateManagementGroupDetails details = null, IEnumerable children = null) - { - children ??= new List(); - - return new ManagementGroupCreateOrUpdateContent( - id, - resourceType, - name, - tenantId, - displayName, - details, - children?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The version number of the object. - /// The date and time when this object was last updated. - /// The identity of the principal or process that updated the object. - /// (Optional) The ID of the parent management group used during creation. - /// A new instance for mocking. - public static CreateManagementGroupDetails CreateManagementGroupDetails(int? version = null, DateTimeOffset? updatedOn = null, string updatedBy = null, ManagementGroupParentCreateOptions parent = null) - { - return new CreateManagementGroupDetails(version, updatedOn, updatedBy, parent, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The name of the parent management group. - /// The friendly name of the parent management group. - /// A new instance for mocking. - public static ManagementGroupParentCreateOptions ManagementGroupParentCreateOptions(string id = null, string name = null, string displayName = null) - { - return new ManagementGroupParentCreateOptions(id, name, displayName, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The fully qualified resource type which includes provider namespace (e.g. Microsoft.Management/managementGroups). - /// The fully qualified ID for the child resource (management group or subscription). For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000. - /// The name of the child entity. - /// The friendly name of the child resource. - /// The list of children. - /// A new instance for mocking. - public static ManagementGroupChildOptions ManagementGroupChildOptions(ManagementGroupChildType? childType = null, string id = null, string name = null, string displayName = null, IEnumerable children = null) - { - children ??= new List(); - - return new ManagementGroupChildOptions( - childType, - id, - name, - displayName, - children?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The friendly name of the management group. - /// The ID of the parent management group. - /// A new instance for mocking. - public static DescendantData DescendantData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, string displayName = null, ResourceIdentifier parentId = null) - { - return new DescendantData( - id, - name, - resourceType, - systemData, - displayName, - parentId != null ? new DescendantParentGroupInfo(parentId, serializedAdditionalRawData: null) : null, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The AAD Tenant ID associated with the subscription. For example, 00000000-0000-0000-0000-000000000000. - /// The friendly name of the subscription. - /// The ID of the parent management group. - /// The state of the subscription. - /// A new instance for mocking. - public static ManagementGroupSubscriptionData ManagementGroupSubscriptionData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, string tenant = null, string displayName = null, ResourceIdentifier parentId = null, string state = null) - { - return new ManagementGroupSubscriptionData( - id, - name, - resourceType, - systemData, - tenant, - displayName, - parentId != null ? new DescendantParentGroupInfo(parentId, serializedAdditionalRawData: null) : null, - state, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// Required. True indicates name is valid and available. False indicates the name is invalid, unavailable, or both. - /// Required if nameAvailable == false. Invalid indicates the name provided does not match the resource provider's naming requirements (incorrect length, unsupported characters, etc.) AlreadyExists indicates that the name is already in use and is therefore unavailable. - /// Required if nameAvailable == false. Localized. If reason == invalid, provide the user with the reason why the given name is invalid, and provide the resource naming requirements so that the user can select a valid name. If reason == AlreadyExists, explain that is already in use, and direct them to select a different name. - /// A new instance for mocking. - public static ManagementGroupNameAvailabilityResult ManagementGroupNameAvailabilityResult(bool? nameAvailable = null, ManagementGroupNameUnavailableReason? reason = null, string message = null) - { - return new ManagementGroupNameAvailabilityResult(nameAvailable, reason, message, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The AAD Tenant ID associated with the entity. For example, 00000000-0000-0000-0000-000000000000. - /// The friendly name of the management group. - /// (Optional) The ID of the parent management group. - /// The users specific permissions to this item. - /// The users specific permissions to this item. - /// Number of Descendants. - /// Number of children is the number of Groups and Subscriptions that are exactly one level underneath the current Group. - /// Number of children is the number of Groups that are exactly one level underneath the current Group. - /// The parent display name chain from the root group to the immediate parent. - /// The parent name chain from the root group to the immediate parent. - /// A new instance for mocking. - public static EntityData EntityData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, Guid? tenantId = null, string displayName = null, ResourceIdentifier parentId = null, EntityPermission? permissions = null, EntityPermission? inheritedPermissions = null, int? numberOfDescendants = null, int? numberOfChildren = null, int? numberOfChildGroups = null, IEnumerable parentDisplayNameChain = null, IEnumerable parentNameChain = null) - { - parentDisplayNameChain ??= new List(); - parentNameChain ??= new List(); - - return new EntityData( - id, - name, - resourceType, - systemData, - tenantId, - displayName, - parentId != null ? ResourceManagerModelFactory.SubResource(parentId) : null, - permissions, - inheritedPermissions, - numberOfDescendants, - numberOfChildren, - numberOfChildGroups, - parentDisplayNameChain?.ToList(), - parentNameChain?.ToList(), - serializedAdditionalRawData: null); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/EntitiesRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/EntitiesRestOperations.cs deleted file mode 100644 index e69f3eae1e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/EntitiesRestOperations.cs +++ /dev/null @@ -1,337 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups.Models; - -namespace Azure.ResourceManager.ManagementGroups -{ - internal partial class EntitiesRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of EntitiesRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public EntitiesRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2021-04-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateListRequestUri(string skipToken, int? skip, int? top, string select, EntitySearchOption? search, string filter, EntityViewOption? view, string groupName, string cacheControl) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/getEntities", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (skipToken != null) - { - uri.AppendQuery("$skiptoken", skipToken, true); - } - if (skip != null) - { - uri.AppendQuery("$skip", skip.Value, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - if (select != null) - { - uri.AppendQuery("$select", select, true); - } - if (search != null) - { - uri.AppendQuery("$search", search.Value.ToString(), true); - } - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - if (view != null) - { - uri.AppendQuery("$view", view.Value.ToString(), true); - } - if (groupName != null) - { - uri.AppendQuery("groupName", groupName, true); - } - return uri; - } - - internal HttpMessage CreateListRequest(string skipToken, int? skip, int? top, string select, EntitySearchOption? search, string filter, EntityViewOption? view, string groupName, string cacheControl) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/getEntities", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (skipToken != null) - { - uri.AppendQuery("$skiptoken", skipToken, true); - } - if (skip != null) - { - uri.AppendQuery("$skip", skip.Value, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - if (select != null) - { - uri.AppendQuery("$select", select, true); - } - if (search != null) - { - uri.AppendQuery("$search", search.Value.ToString(), true); - } - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - if (view != null) - { - uri.AppendQuery("$view", view.Value.ToString(), true); - } - if (groupName != null) - { - uri.AppendQuery("groupName", groupName, true); - } - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// List all entities (Management Groups, Subscriptions, etc.) for the authenticated user. - /// - /// - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of entities to skip over when retrieving results. Passing this in will override $skipToken. - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// This parameter specifies the fields to include in the response. Can include any combination of Name,DisplayName,Type,ParentDisplayNameChain,ParentChain, e.g. '$select=Name,DisplayName,Type,ParentDisplayNameChain,ParentNameChain'. When specified the $select parameter can override select in $skipToken. - /// - /// The $search parameter is used in conjunction with the $filter parameter to return three different outputs depending on the parameter passed in. - /// With $search=AllowedParents the API will return the entity info of all groups that the requested entity will be able to reparent to as determined by the user's permissions. - /// With $search=AllowedChildren the API will return the entity info of all entities that can be added as children of the requested entity. - /// With $search=ParentAndFirstLevelChildren the API will return the parent and first level of children that the user has either direct access to or indirect access via one of their descendants. - /// With $search=ParentOnly the API will return only the group if the user has access to at least one of the descendants of the group. - /// With $search=ChildrenOnly the API will return only the first level of children of the group entity info specified in $filter. The user must have direct access to the children entities or one of it's descendants for it to show up in the results. - /// - /// The filter parameter allows you to filter on the the name or display name fields. You can check for equality on the name field (e.g. name eq '{entityName}') and you can check for substrings on either the name or display name fields(e.g. contains(name, '{substringToSearch}'), contains(displayName, '{substringToSearch')). Note that the '{entityName}' and '{substringToSearch}' fields are checked case insensitively. - /// The view parameter allows clients to filter the type of data that is returned by the getEntities call. - /// A filter which allows the get entities call to focus on a particular group (i.e. "$filter=name eq 'groupName'"). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public async Task> ListAsync(string skipToken = null, int? skip = null, int? top = null, string select = null, EntitySearchOption? search = null, string filter = null, EntityViewOption? view = null, string groupName = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(skipToken, skip, top, select, search, filter, view, groupName, cacheControl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - EntityListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = EntityListResult.DeserializeEntityListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// List all entities (Management Groups, Subscriptions, etc.) for the authenticated user. - /// - /// - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of entities to skip over when retrieving results. Passing this in will override $skipToken. - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// This parameter specifies the fields to include in the response. Can include any combination of Name,DisplayName,Type,ParentDisplayNameChain,ParentChain, e.g. '$select=Name,DisplayName,Type,ParentDisplayNameChain,ParentNameChain'. When specified the $select parameter can override select in $skipToken. - /// - /// The $search parameter is used in conjunction with the $filter parameter to return three different outputs depending on the parameter passed in. - /// With $search=AllowedParents the API will return the entity info of all groups that the requested entity will be able to reparent to as determined by the user's permissions. - /// With $search=AllowedChildren the API will return the entity info of all entities that can be added as children of the requested entity. - /// With $search=ParentAndFirstLevelChildren the API will return the parent and first level of children that the user has either direct access to or indirect access via one of their descendants. - /// With $search=ParentOnly the API will return only the group if the user has access to at least one of the descendants of the group. - /// With $search=ChildrenOnly the API will return only the first level of children of the group entity info specified in $filter. The user must have direct access to the children entities or one of it's descendants for it to show up in the results. - /// - /// The filter parameter allows you to filter on the the name or display name fields. You can check for equality on the name field (e.g. name eq '{entityName}') and you can check for substrings on either the name or display name fields(e.g. contains(name, '{substringToSearch}'), contains(displayName, '{substringToSearch')). Note that the '{entityName}' and '{substringToSearch}' fields are checked case insensitively. - /// The view parameter allows clients to filter the type of data that is returned by the getEntities call. - /// A filter which allows the get entities call to focus on a particular group (i.e. "$filter=name eq 'groupName'"). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - public Response List(string skipToken = null, int? skip = null, int? top = null, string select = null, EntitySearchOption? search = null, string filter = null, EntityViewOption? view = null, string groupName = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(skipToken, skip, top, select, search, filter, view, groupName, cacheControl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - EntityListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = EntityListResult.DeserializeEntityListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string skipToken, int? skip, int? top, string select, EntitySearchOption? search, string filter, EntityViewOption? view, string groupName, string cacheControl) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string skipToken, int? skip, int? top, string select, EntitySearchOption? search, string filter, EntityViewOption? view, string groupName, string cacheControl) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// List all entities (Management Groups, Subscriptions, etc.) for the authenticated user. - /// - /// - /// The URL to the next page of results. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of entities to skip over when retrieving results. Passing this in will override $skipToken. - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// This parameter specifies the fields to include in the response. Can include any combination of Name,DisplayName,Type,ParentDisplayNameChain,ParentChain, e.g. '$select=Name,DisplayName,Type,ParentDisplayNameChain,ParentNameChain'. When specified the $select parameter can override select in $skipToken. - /// - /// The $search parameter is used in conjunction with the $filter parameter to return three different outputs depending on the parameter passed in. - /// With $search=AllowedParents the API will return the entity info of all groups that the requested entity will be able to reparent to as determined by the user's permissions. - /// With $search=AllowedChildren the API will return the entity info of all entities that can be added as children of the requested entity. - /// With $search=ParentAndFirstLevelChildren the API will return the parent and first level of children that the user has either direct access to or indirect access via one of their descendants. - /// With $search=ParentOnly the API will return only the group if the user has access to at least one of the descendants of the group. - /// With $search=ChildrenOnly the API will return only the first level of children of the group entity info specified in $filter. The user must have direct access to the children entities or one of it's descendants for it to show up in the results. - /// - /// The filter parameter allows you to filter on the the name or display name fields. You can check for equality on the name field (e.g. name eq '{entityName}') and you can check for substrings on either the name or display name fields(e.g. contains(name, '{substringToSearch}'), contains(displayName, '{substringToSearch')). Note that the '{entityName}' and '{substringToSearch}' fields are checked case insensitively. - /// The view parameter allows clients to filter the type of data that is returned by the getEntities call. - /// A filter which allows the get entities call to focus on a particular group (i.e. "$filter=name eq 'groupName'"). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - public async Task> ListNextPageAsync(string nextLink, string skipToken = null, int? skip = null, int? top = null, string select = null, EntitySearchOption? search = null, string filter = null, EntityViewOption? view = null, string groupName = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink, skipToken, skip, top, select, search, filter, view, groupName, cacheControl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - EntityListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = EntityListResult.DeserializeEntityListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// List all entities (Management Groups, Subscriptions, etc.) for the authenticated user. - /// - /// - /// The URL to the next page of results. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of entities to skip over when retrieving results. Passing this in will override $skipToken. - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// This parameter specifies the fields to include in the response. Can include any combination of Name,DisplayName,Type,ParentDisplayNameChain,ParentChain, e.g. '$select=Name,DisplayName,Type,ParentDisplayNameChain,ParentNameChain'. When specified the $select parameter can override select in $skipToken. - /// - /// The $search parameter is used in conjunction with the $filter parameter to return three different outputs depending on the parameter passed in. - /// With $search=AllowedParents the API will return the entity info of all groups that the requested entity will be able to reparent to as determined by the user's permissions. - /// With $search=AllowedChildren the API will return the entity info of all entities that can be added as children of the requested entity. - /// With $search=ParentAndFirstLevelChildren the API will return the parent and first level of children that the user has either direct access to or indirect access via one of their descendants. - /// With $search=ParentOnly the API will return only the group if the user has access to at least one of the descendants of the group. - /// With $search=ChildrenOnly the API will return only the first level of children of the group entity info specified in $filter. The user must have direct access to the children entities or one of it's descendants for it to show up in the results. - /// - /// The filter parameter allows you to filter on the the name or display name fields. You can check for equality on the name field (e.g. name eq '{entityName}') and you can check for substrings on either the name or display name fields(e.g. contains(name, '{substringToSearch}'), contains(displayName, '{substringToSearch')). Note that the '{entityName}' and '{substringToSearch}' fields are checked case insensitively. - /// The view parameter allows clients to filter the type of data that is returned by the getEntities call. - /// A filter which allows the get entities call to focus on a particular group (i.e. "$filter=name eq 'groupName'"). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - public Response ListNextPage(string nextLink, string skipToken = null, int? skip = null, int? top = null, string select = null, EntitySearchOption? search = null, string filter = null, EntityViewOption? view = null, string groupName = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink, skipToken, skip, top, select, search, filter, view, groupName, cacheControl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - EntityListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = EntityListResult.DeserializeEntityListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/ManagementGroupSubscriptionsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/ManagementGroupSubscriptionsRestOperations.cs deleted file mode 100644 index 5a9ce3d7e5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/ManagementGroupSubscriptionsRestOperations.cs +++ /dev/null @@ -1,517 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups.Models; - -namespace Azure.ResourceManager.ManagementGroups -{ - internal partial class ManagementGroupSubscriptionsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of ManagementGroupSubscriptionsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public ManagementGroupSubscriptionsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2021-04-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateCreateRequestUri(string groupId, string subscriptionId, string cacheControl) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateRequest(string groupId, string subscriptionId, string cacheControl) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// Associates existing subscription with the management group. - /// - /// - /// Management Group ID. - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> CreateAsync(string groupId, string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateCreateRequest(groupId, subscriptionId, cacheControl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupSubscriptionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementGroupSubscriptionData.DeserializeManagementGroupSubscriptionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// Associates existing subscription with the management group. - /// - /// - /// Management Group ID. - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Create(string groupId, string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateCreateRequest(groupId, subscriptionId, cacheControl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupSubscriptionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementGroupSubscriptionData.DeserializeManagementGroupSubscriptionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteRequestUri(string groupId, string subscriptionId, string cacheControl) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteRequest(string groupId, string subscriptionId, string cacheControl) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// De-associates subscription from the management group. - /// - /// - /// Management Group ID. - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task DeleteAsync(string groupId, string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateDeleteRequest(groupId, subscriptionId, cacheControl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// De-associates subscription from the management group. - /// - /// - /// Management Group ID. - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Delete(string groupId, string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateDeleteRequest(groupId, subscriptionId, cacheControl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetSubscriptionRequestUri(string groupId, string subscriptionId, string cacheControl) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetSubscriptionRequest(string groupId, string subscriptionId, string cacheControl) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// Retrieves details about given subscription which is associated with the management group. - /// - /// - /// Management Group ID. - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> GetSubscriptionAsync(string groupId, string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateGetSubscriptionRequest(groupId, subscriptionId, cacheControl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupSubscriptionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementGroupSubscriptionData.DeserializeManagementGroupSubscriptionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ManagementGroupSubscriptionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// Retrieves details about given subscription which is associated with the management group. - /// - /// - /// Management Group ID. - /// Subscription ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response GetSubscription(string groupId, string subscriptionId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateGetSubscriptionRequest(groupId, subscriptionId, cacheControl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupSubscriptionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementGroupSubscriptionData.DeserializeManagementGroupSubscriptionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ManagementGroupSubscriptionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetSubscriptionsUnderManagementGroupRequestUri(string groupId, string skipToken) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/subscriptions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (skipToken != null) - { - uri.AppendQuery("$skiptoken", skipToken, true); - } - return uri; - } - - internal HttpMessage CreateGetSubscriptionsUnderManagementGroupRequest(string groupId, string skipToken) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/subscriptions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (skipToken != null) - { - uri.AppendQuery("$skiptoken", skipToken, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// Retrieves details about all subscriptions which are associated with the management group. - /// - /// - /// Management Group ID. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetSubscriptionsUnderManagementGroupAsync(string groupId, string skipToken = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetSubscriptionsUnderManagementGroupRequest(groupId, skipToken); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ListSubscriptionUnderManagementGroup value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ListSubscriptionUnderManagementGroup.DeserializeListSubscriptionUnderManagementGroup(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// Retrieves details about all subscriptions which are associated with the management group. - /// - /// - /// Management Group ID. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response GetSubscriptionsUnderManagementGroup(string groupId, string skipToken = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetSubscriptionsUnderManagementGroupRequest(groupId, skipToken); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ListSubscriptionUnderManagementGroup value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ListSubscriptionUnderManagementGroup.DeserializeListSubscriptionUnderManagementGroup(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetSubscriptionsUnderManagementGroupNextPageRequestUri(string nextLink, string groupId, string skipToken) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateGetSubscriptionsUnderManagementGroupNextPageRequest(string nextLink, string groupId, string skipToken) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// Retrieves details about all subscriptions which are associated with the management group. - /// - /// - /// The URL to the next page of results. - /// Management Group ID. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetSubscriptionsUnderManagementGroupNextPageAsync(string nextLink, string groupId, string skipToken = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetSubscriptionsUnderManagementGroupNextPageRequest(nextLink, groupId, skipToken); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ListSubscriptionUnderManagementGroup value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ListSubscriptionUnderManagementGroup.DeserializeListSubscriptionUnderManagementGroup(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// Retrieves details about all subscriptions which are associated with the management group. - /// - /// - /// The URL to the next page of results. - /// Management Group ID. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response GetSubscriptionsUnderManagementGroupNextPage(string nextLink, string groupId, string skipToken = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetSubscriptionsUnderManagementGroupNextPageRequest(nextLink, groupId, skipToken); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ListSubscriptionUnderManagementGroup value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ListSubscriptionUnderManagementGroup.DeserializeListSubscriptionUnderManagementGroup(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/ManagementGroupsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/ManagementGroupsRestOperations.cs deleted file mode 100644 index f284696f8b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/ManagementGroupsRestOperations.cs +++ /dev/null @@ -1,897 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups.Models; - -namespace Azure.ResourceManager.ManagementGroups -{ - internal partial class ManagementGroupsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of ManagementGroupsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public ManagementGroupsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2021-04-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateListRequestUri(string cacheControl, string skipToken) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (skipToken != null) - { - uri.AppendQuery("$skiptoken", skipToken, true); - } - return uri; - } - - internal HttpMessage CreateListRequest(string cacheControl, string skipToken) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (skipToken != null) - { - uri.AppendQuery("$skiptoken", skipToken, true); - } - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// List management groups for the authenticated user. - /// - /// - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - public async Task> ListAsync(string cacheControl = null, string skipToken = null, CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(cacheControl, skipToken); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementGroupListResult.DeserializeManagementGroupListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// List management groups for the authenticated user. - /// - /// - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - public Response List(string cacheControl = null, string skipToken = null, CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(cacheControl, skipToken); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementGroupListResult.DeserializeManagementGroupListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetRequestUri(string groupId, ManagementGroupExpandType? expand, bool? recurse, string filter, string cacheControl) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendQuery("api-version", _apiVersion, true); - if (expand != null) - { - uri.AppendQuery("$expand", expand.Value.ToString(), true); - } - if (recurse != null) - { - uri.AppendQuery("$recurse", recurse.Value, true); - } - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - return uri; - } - - internal HttpMessage CreateGetRequest(string groupId, ManagementGroupExpandType? expand, bool? recurse, string filter, string cacheControl) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendQuery("api-version", _apiVersion, true); - if (expand != null) - { - uri.AppendQuery("$expand", expand.Value.ToString(), true); - } - if (recurse != null) - { - uri.AppendQuery("$recurse", recurse.Value, true); - } - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// Get the details of the management group. - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetAsync(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetRequest(groupId, expand, recurse, filter, cacheControl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementGroupData.DeserializeManagementGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ManagementGroupData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// Get the details of the management group. - /// - /// - /// Management Group ID. - /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. - /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. - /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription'). - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response Get(string groupId, ManagementGroupExpandType? expand = null, bool? recurse = null, string filter = null, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetRequest(groupId, expand, recurse, filter, cacheControl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementGroupData.DeserializeManagementGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ManagementGroupData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateCreateOrUpdateRequestUri(string groupId, ManagementGroupCreateOrUpdateContent content, string cacheControl) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateRequest(string groupId, ManagementGroupCreateOrUpdateContent content, string cacheControl) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content0 = new Utf8JsonRequestContent(); - content0.JsonWriter.WriteObjectValue(content, ModelSerializationExtensions.WireOptions); - request.Content = content0; - _userAgent.Apply(message); - return message; - } - - /// - /// Create or update a management group. - /// If a management group is already created and a subsequent create request is issued with different properties, the management group properties will be updated. - /// - /// - /// Management Group ID. - /// Management group creation parameters. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task CreateOrUpdateAsync(string groupId, ManagementGroupCreateOrUpdateContent content, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNull(content, nameof(content)); - - using var message = CreateCreateOrUpdateRequest(groupId, content, cacheControl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// Create or update a management group. - /// If a management group is already created and a subsequent create request is issued with different properties, the management group properties will be updated. - /// - /// - /// Management Group ID. - /// Management group creation parameters. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response CreateOrUpdate(string groupId, ManagementGroupCreateOrUpdateContent content, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNull(content, nameof(content)); - - using var message = CreateCreateOrUpdateRequest(groupId, content, cacheControl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateUpdateRequestUri(string groupId, ManagementGroupPatch patch, string cacheControl) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateUpdateRequest(string groupId, ManagementGroupPatch patch, string cacheControl) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Patch; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(patch, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// - /// Update a management group. - /// - /// - /// Management Group ID. - /// Management group patch parameters. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> UpdateAsync(string groupId, ManagementGroupPatch patch, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNull(patch, nameof(patch)); - - using var message = CreateUpdateRequest(groupId, patch, cacheControl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementGroupData.DeserializeManagementGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// Update a management group. - /// - /// - /// Management Group ID. - /// Management group patch parameters. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response Update(string groupId, ManagementGroupPatch patch, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - Argument.AssertNotNull(patch, nameof(patch)); - - using var message = CreateUpdateRequest(groupId, patch, cacheControl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementGroupData.DeserializeManagementGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteRequestUri(string groupId, string cacheControl) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteRequest(string groupId, string cacheControl) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// Delete management group. - /// If a management group contains child resources, the request will fail. - /// - /// - /// Management Group ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task DeleteAsync(string groupId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateDeleteRequest(groupId, cacheControl); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 202: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// Delete management group. - /// If a management group contains child resources, the request will fail. - /// - /// - /// Management Group ID. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response Delete(string groupId, string cacheControl = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateDeleteRequest(groupId, cacheControl); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 202: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetDescendantsRequestUri(string groupId, string skipToken, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/descendants", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (skipToken != null) - { - uri.AppendQuery("$skiptoken", skipToken, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - return uri; - } - - internal HttpMessage CreateGetDescendantsRequest(string groupId, string skipToken, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(groupId, true); - uri.AppendPath("/descendants", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (skipToken != null) - { - uri.AppendQuery("$skiptoken", skipToken, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// List all entities that descend from a management group. - /// - /// - /// Management Group ID. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetDescendantsAsync(string groupId, string skipToken = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetDescendantsRequest(groupId, skipToken, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - DescendantListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = DescendantListResult.DeserializeDescendantListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// List all entities that descend from a management group. - /// - /// - /// Management Group ID. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response GetDescendants(string groupId, string skipToken = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetDescendantsRequest(groupId, skipToken, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - DescendantListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = DescendantListResult.DeserializeDescendantListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateCheckNameAvailabilityRequestUri(ManagementGroupNameAvailabilityContent content) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/checkNameAvailability", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCheckNameAvailabilityRequest(ManagementGroupNameAvailabilityContent content) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/checkNameAvailability", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content0 = new Utf8JsonRequestContent(); - content0.JsonWriter.WriteObjectValue(content, ModelSerializationExtensions.WireOptions); - request.Content = content0; - _userAgent.Apply(message); - return message; - } - - /// Checks if the specified management group name is valid and unique. - /// Management group name availability check parameters. - /// The cancellation token to use. - /// is null. - public async Task> CheckNameAvailabilityAsync(ManagementGroupNameAvailabilityContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(content, nameof(content)); - - using var message = CreateCheckNameAvailabilityRequest(content); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupNameAvailabilityResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementGroupNameAvailabilityResult.DeserializeManagementGroupNameAvailabilityResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Checks if the specified management group name is valid and unique. - /// Management group name availability check parameters. - /// The cancellation token to use. - /// is null. - public Response CheckNameAvailability(ManagementGroupNameAvailabilityContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(content, nameof(content)); - - using var message = CreateCheckNameAvailabilityRequest(content); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupNameAvailabilityResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementGroupNameAvailabilityResult.DeserializeManagementGroupNameAvailabilityResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string cacheControl, string skipToken) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string cacheControl, string skipToken) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - if (cacheControl != null) - { - request.Headers.Add("Cache-Control", cacheControl); - } - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// List management groups for the authenticated user. - /// - /// - /// The URL to the next page of results. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// is null. - public async Task> ListNextPageAsync(string nextLink, string cacheControl = null, string skipToken = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink, cacheControl, skipToken); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementGroupListResult.DeserializeManagementGroupListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// List management groups for the authenticated user. - /// - /// - /// The URL to the next page of results. - /// Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// The cancellation token to use. - /// is null. - public Response ListNextPage(string nextLink, string cacheControl = null, string skipToken = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink, cacheControl, skipToken); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementGroupListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementGroupListResult.DeserializeManagementGroupListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetDescendantsNextPageRequestUri(string nextLink, string groupId, string skipToken, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateGetDescendantsNextPageRequest(string nextLink, string groupId, string skipToken, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// - /// List all entities that descend from a management group. - /// - /// - /// The URL to the next page of results. - /// Management Group ID. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetDescendantsNextPageAsync(string nextLink, string groupId, string skipToken = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetDescendantsNextPageRequest(nextLink, groupId, skipToken, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - DescendantListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = DescendantListResult.DeserializeDescendantListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// - /// List all entities that descend from a management group. - /// - /// - /// The URL to the next page of results. - /// Management Group ID. - /// - /// Page continuation token is only used if a previous operation returned a partial result. - /// If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls. - /// - /// - /// Number of elements to return when retrieving results. Passing this in will override $skipToken. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response GetDescendantsNextPage(string nextLink, string groupId, string skipToken = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(groupId, nameof(groupId)); - - using var message = CreateGetDescendantsNextPageRequest(nextLink, groupId, skipToken, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - DescendantListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = DescendantListResult.DeserializeDescendantListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Properties/AssemblyInfo.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Properties/AssemblyInfo.cs deleted file mode 100644 index 3a31e4dd1d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.Runtime.CompilerServices; -using Azure.Core; - -[assembly: AzureResourceProviderNamespace("Microsoft.Resources")] - -[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] -[assembly: InternalsVisibleTo("Azure.ResourceManager.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] -[assembly: InternalsVisibleTo("Azure.ResourceManager.Perf, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ProviderConstants.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ProviderConstants.cs deleted file mode 100644 index dbce6211e2..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ProviderConstants.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager -{ - internal static class ProviderConstants - { - public static string DefaultProviderNamespace { get; } = ClientDiagnostics.GetResourceProviderNamespace(typeof(ProviderConstants).Assembly); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/RehydrationOperation.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/RehydrationOperation.cs deleted file mode 100644 index 7fe620e46e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/RehydrationOperation.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; -using Azure.Core; - -namespace Azure.ResourceManager -{ - internal class RehydrationOperation : ArmOperation - { - private readonly NextLinkOperationImplementation _nextLinkOperation; - private readonly OperationInternal _operation; - - public RehydrationOperation(NextLinkOperationImplementation nextLinkOperation, OperationState operationState, ClientOptions? options = null) - { - _nextLinkOperation = nextLinkOperation; - _operation = operationState.HasCompleted - ? new OperationInternal(operationState) - : new OperationInternal(nextLinkOperation, new ClientDiagnostics(options ?? ClientOptions.Default), operationState.RawResponse); - } - - public override string Id => _nextLinkOperation.OperationId; - - public override RehydrationToken? GetRehydrationToken() => _nextLinkOperation?.GetRehydrationToken(); - - public override bool HasCompleted => _operation.HasCompleted; - - public override Response GetRawResponse() => _operation.RawResponse; - - public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); - - public override ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/RehydrationOperationOfT.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/RehydrationOperationOfT.cs deleted file mode 100644 index 21b1298880..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/RehydrationOperationOfT.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager -{ -#pragma warning disable SA1649 // File name should match first type name - internal class RehydrationOperation : ArmOperation where T : notnull -#pragma warning restore SA1649 // File name should match first type name - { - private readonly OperationInternal _operation; - private readonly NextLinkOperationImplementation _nextLinkOperation; - - public RehydrationOperation(NextLinkOperationImplementation nextLinkOperation, OperationState operationState, IOperation operation, ClientOptions? options = null) - { - _nextLinkOperation = nextLinkOperation; - _operation = operationState.HasCompleted - ? new OperationInternal(operationState) - : new OperationInternal(operation, new ClientDiagnostics(options ?? ClientOptions.Default), operationState.RawResponse); - } - - public override T Value => _operation.Value; - - public override bool HasValue => _operation.HasValue; - - public override string Id => _nextLinkOperation.OperationId; - - public override bool HasCompleted => _operation.HasCompleted; - - public override Response GetRawResponse() => _operation.RawResponse; - - public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); - - public override ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/ResourceManagerExtensions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/ResourceManagerExtensions.cs deleted file mode 100644 index 19a2d39743..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/ResourceManagerExtensions.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using Azure.Core; -using Azure.ResourceManager.Resources; -using System; - -namespace Azure.ResourceManager -{ - /// - /// Extension class for resource manager. - /// - internal static class ResourceManagerExtensions - { - /// - /// Gets the correlation id from x-ms-correlation-id. - /// - public static string GetCorrelationId(this Response response) - { - string correlationId = null; - response.Headers.TryGetValue("x-ms-correlation-request-id", out correlationId); - return correlationId; - } - - internal static ResourceIdentifier GetSubscriptionResourceIdentifier(this ResourceIdentifier id) - { - if (id.ResourceType == SubscriptionResource.ResourceType) - return id; - - ResourceIdentifier parent = id.Parent; - while (parent != null && parent.ResourceType != SubscriptionResource.ResourceType) - { - parent = parent.Parent; - } - - return parent?.ResourceType == SubscriptionResource.ResourceType ? parent : null; - } - - internal static string GetManifestName(this AzureStackProfile profile) - { - var namePrefix = "Azure.ResourceManager.Assets.Profile."; - var nameSuffix = profile switch - { - AzureStackProfile.Profile20200901Hybrid => "2020-09-01-hybrid.json", - _ => throw new ArgumentOutOfRangeException(nameof(profile), profile, null) - }; - return namePrefix + nameSuffix; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ArmClient.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ArmClient.cs deleted file mode 100644 index e26f631cc1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ArmClient.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using Azure.Core; -using Azure.ResourceManager.Resources; - -namespace Azure.ResourceManager -{ - /// - /// The entry point for all ARM clients. - /// - [CodeGenSuppress("GetTenantResource", typeof(ResourceIdentifier))] - public partial class ArmClient - { - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual GenericResource GetGenericResource(ResourceIdentifier id) - { - GenericResource.ValidateResourceId(id); - return new GenericResource(this, id); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ArmRestApiCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ArmRestApiCollection.cs deleted file mode 100644 index 25e587549e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ArmRestApiCollection.cs +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class which represents the RestApis for a given azure namespace. - /// - public partial class ArmRestApiCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _clientDiagnostics; - private readonly string _nameSpace; - private readonly ResourceProviderCollection _providerCollection; - - /// Represents the REST operations. - private RestOperations _restClient; - - /// Initializes a new instance of the class for mocking. - protected ArmRestApiCollection() - { - } - - /// Initializes a new instance of RestApiCollection class. - /// The resource representing the parent resource. - /// The namespace for the rest apis. - internal ArmRestApiCollection(ArmResource operation, string nameSpace) - : base(operation.Client, operation.Id) - { - _clientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", nameSpace, Diagnostics); - _nameSpace = nameSpace; - _providerCollection = new ResourceProviderCollection(Client.GetSubscriptionResource(Id)); - } - - private RestOperations GetRestClient(CancellationToken cancellationToken = default) - { - return _restClient ??= new RestOperations( - _nameSpace, - _providerCollection.GetApiVersion(new ResourceType($"{_nameSpace}/operations"), cancellationToken), - _clientDiagnostics, - Pipeline, - Diagnostics.ApplicationId, - Endpoint); - } - - private async Task GetRestClientAsync(CancellationToken cancellationToken = default) - { - return _restClient ??= new RestOperations( - _nameSpace, - await _providerCollection.GetApiVersionAsync(new ResourceType($"{_nameSpace}/operations"), cancellationToken).ConfigureAwait(false), - _clientDiagnostics, - Pipeline, - Diagnostics.ApplicationId, - Endpoint); - } - - /// Gets a list of operations. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(CancellationToken cancellationToken = default) - { - Page FirstPageFunc(int? pageSizeHint) - { - using var scope = _clientDiagnostics.CreateScope("ArmRestApiCollection.GetAll"); - scope.Start(); - try - { - var response = GetRestClient().List(cancellationToken: cancellationToken); - return Page.FromValues(response.Value.Value, null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - return PageableHelpers.CreateEnumerable(FirstPageFunc, null); - } - - /// Gets a list of operations. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(CancellationToken cancellationToken = default) - { - async Task> FirstPageFunc(int? pageSizeHint) - { - using var scope = _clientDiagnostics.CreateScope("ArmRestApiCollection.GetAll"); - scope.Start(); - try - { - var restClient = await GetRestClientAsync().ConfigureAwait(false); - var response = await restClient.ListAsync(cancellationToken: cancellationToken).ConfigureAwait(false); - return Page.FromValues(response.Value.Value, null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, null); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Extensions/ArmResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Extensions/ArmResource.cs deleted file mode 100644 index 451ced6807..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Extensions/ArmResource.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using Azure.Core; -using Azure.ResourceManager.Resources; - -namespace Azure.ResourceManager -{ - public partial class ArmResource - { - /// Gets an object representing a TagResource along with the instance operations that can be performed on it in the ArmResource. - /// Returns a object. - public virtual TagResource GetTagResource() - { - return GetCachedClient(client => new TagResource(client, new ResourceIdentifier(Id.ToString() + "/providers/Microsoft.Resources/tags/default"))); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/FeatureResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/FeatureResource.cs deleted file mode 100644 index ebfa136947..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/FeatureResource.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using Azure.Core; - -[assembly:CodeGenSuppressType("ErrorDefinition")] -[assembly:CodeGenSuppressType("FeatureErrorResponse")] -namespace Azure.ResourceManager.Resources -{ - /// A Class representing a Feature along with the instance operations that can be performed on it. - public partial class FeatureResource : ArmResource - { - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType.GetLastType() != "features") - { - throw new InvalidOperationException($"Invalid resourcetype found when intializing FeatureOperations: {id.ResourceType}"); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/GenericResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/GenericResource.cs deleted file mode 100644 index 7de2f6b25d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/GenericResource.cs +++ /dev/null @@ -1,433 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -[assembly: CodeGenSuppressType("GenericResourceFilter")] -[assembly: CodeGenSuppressType("GenericResource")] -[assembly: CodeGenSuppressType("GenericResourceIdentityType")] -namespace Azure.ResourceManager.Resources -{ - /// A Class representing a GenericResource along with the instance operations that can be performed on it. - public partial class GenericResource : ArmResource - { - private readonly ClientDiagnostics _clientDiagnostics; - private readonly ResourcesRestOperations _resourcesRestClient; - private readonly GenericResourceData _data; - private readonly ResourceProviderCollection _providerCollection; - - /// Initializes a new instance of the class for mocking. - protected GenericResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal GenericResource(ArmClient client, GenericResourceData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal GenericResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - ResourceIdentifier subscription = Id.GetSubscriptionResourceIdentifier(); - if (subscription == null) - { - throw new ArgumentException("Only resource in a subscription is supported"); - } - _clientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", Id.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(Id.ResourceType, out string apiVersion); - _resourcesRestClient = new ResourcesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, apiVersion); - _providerCollection = new ResourceProviderCollection(Client.GetSubscriptionResource(subscription)); - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual GenericResourceData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - -#pragma warning disable CA1801 // Review unused parameters - internal static void ValidateResourceId(ResourceIdentifier id) -#pragma warning restore CA1801 // Review unused parameters - { - //no op but here for code generation - } - - /// RequestPath: /{resourceId} - /// ContextualPath: /{resourceId} - /// OperationId: Resources_GetById - /// Gets a resource by ID. - /// The cancellation token to use. - public async virtual Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _clientDiagnostics.CreateScope("GenericResource.Get"); - scope.Start(); - try - { - var apiVersion = await GetApiVersionAsync(cancellationToken).ConfigureAwait(false); - var response = await _resourcesRestClient.GetByIdAsync(Id, apiVersion, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new GenericResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// RequestPath: /{resourceId} - /// ContextualPath: /{resourceId} - /// OperationId: Resources_GetById - /// Gets a resource by ID. - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _clientDiagnostics.CreateScope("GenericResource.Get"); - scope.Start(); - try - { - var apiVersion = GetApiVersion(cancellationToken); - var response = _resourcesRestClient.GetById(Id, apiVersion, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new GenericResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// RequestPath: /{resourceId} - /// ContextualPath: /{resourceId} - /// OperationId: Resources_DeleteById - /// Deletes a resource by ID. - /// "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public async virtual Task DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _clientDiagnostics.CreateScope("GenericResource.Delete"); - scope.Start(); - try - { - var apiVersion = await GetApiVersionAsync(cancellationToken).ConfigureAwait(false); - var response = await _resourcesRestClient.DeleteByIdAsync(Id, apiVersion, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(_clientDiagnostics, Pipeline, _resourcesRestClient.CreateDeleteByIdRequest(Id, apiVersion).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// RequestPath: /{resourceId} - /// ContextualPath: /{resourceId} - /// OperationId: Resources_DeleteById - /// Deletes a resource by ID. - /// "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _clientDiagnostics.CreateScope("GenericResource.Delete"); - scope.Start(); - try - { - var apiVersion = GetApiVersion(cancellationToken); - var response = _resourcesRestClient.DeleteById(Id, apiVersion, cancellationToken); - var operation = new ResourcesArmOperation(_clientDiagnostics, Pipeline, _resourcesRestClient.CreateDeleteByIdRequest(Id, apiVersion).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Add a tag to the current resource. - /// The key for the tag. - /// The value for the tag. - /// A token to allow the caller to cancel the call to the service. The default value is . - /// The updated resource with the tag added. - public async virtual Task> AddTagAsync(string key, string value, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(key)) - { - throw new ArgumentNullException(nameof(key), $"{nameof(key)} provided cannot be null or a whitespace."); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResource.AddTag"); - scope.Start(); - try - { - var apiVersion = await GetApiVersionAsync(cancellationToken).ConfigureAwait(false); - var tagPatch = new TagResourcePatch(TagPatchMode.Merge, new Tag(new Dictionary { { key, value } }, null), null); - await GetTagResource().UpdateAsync(WaitUntil.Completed, tagPatch, cancellationToken).ConfigureAwait(false); - var originalResponse = await _resourcesRestClient.GetByIdAsync(Id, apiVersion, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new GenericResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Add a tag to the current resource. - /// The key for the tag. - /// The value for the tag. - /// A token to allow the caller to cancel the call to the service. The default value is . - /// The updated resource with the tag added. - public virtual Response AddTag(string key, string value, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(key)) - { - throw new ArgumentNullException(nameof(key), $"{nameof(key)} provided cannot be null or a whitespace."); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResource.AddTag"); - scope.Start(); - try - { - var apiVersion = GetApiVersion(cancellationToken); - var tagPatch = new TagResourcePatch(TagPatchMode.Merge, new Tag(new Dictionary { { key, value } }, null), null); - GetTagResource().Update(WaitUntil.Completed, tagPatch, cancellationToken: cancellationToken); - var originalResponse = _resourcesRestClient.GetById(Id, apiVersion, cancellationToken); - return Response.FromValue(new GenericResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Replace the tags on the resource with the given set. - /// The set of tags to use as replacement. - /// A token to allow the caller to cancel the call to the service. The default value is . - /// The updated resource with the tags replaced. - public async virtual Task> SetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) - { - if (tags == null) - { - throw new ArgumentNullException(nameof(tags), $"{nameof(tags)} provided cannot be null."); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResource.SetTags"); - scope.Start(); - try - { - var apiVersion = await GetApiVersionAsync(cancellationToken).ConfigureAwait(false); - await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, new TagResourceData(new Tag(tags, null)), cancellationToken: cancellationToken).ConfigureAwait(false); - var originalResponse = await _resourcesRestClient.GetByIdAsync(Id, apiVersion, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new GenericResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Replace the tags on the resource with the given set. - /// The set of tags to use as replacement. - /// A token to allow the caller to cancel the call to the service. The default value is . - /// The updated resource with the tags replaced. - public virtual Response SetTags(IDictionary tags, CancellationToken cancellationToken = default) - { - if (tags == null) - { - throw new ArgumentNullException(nameof(tags), $"{nameof(tags)} provided cannot be null."); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResource.SetTags"); - scope.Start(); - try - { - var apiVersion = GetApiVersion(cancellationToken); - GetTagResource().CreateOrUpdate(WaitUntil.Completed, new TagResourceData(new Tag(tags, null)), cancellationToken: cancellationToken); - var originalResponse = _resourcesRestClient.GetById(Id, apiVersion, cancellationToken); - return Response.FromValue(new GenericResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Removes a tag by key from the resource. - /// The key of the tag to remove. - /// A token to allow the caller to cancel the call to the service. The default value is . - /// The updated resource with the tag removed. - public async virtual Task> RemoveTagAsync(string key, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(key)) - { - throw new ArgumentNullException(nameof(key), $"{nameof(key)} provided cannot be null or a whitespace."); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResource.RemoveTag"); - scope.Start(); - try - { - var apiVersion = await GetApiVersionAsync(cancellationToken).ConfigureAwait(false); - var tagPatch = new TagResourcePatch(TagPatchMode.Delete, new Tag(new Dictionary { { key, string.Empty } }, null), null); - await GetTagResource().UpdateAsync(WaitUntil.Completed, tagPatch, cancellationToken: cancellationToken).ConfigureAwait(false); - var originalResponse = await _resourcesRestClient.GetByIdAsync(Id, apiVersion, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new GenericResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Removes a tag by key from the resource. - /// The key of the tag to remove. - /// A token to allow the caller to cancel the call to the service. The default value is . - /// The updated resource with the tag removed. - public virtual Response RemoveTag(string key, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(key)) - { - throw new ArgumentNullException(nameof(key), $"{nameof(key)} provided cannot be null or a whitespace."); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResource.RemoveTag"); - scope.Start(); - try - { - var apiVersion = GetApiVersion(cancellationToken); - var tagPatch = new TagResourcePatch(TagPatchMode.Delete, new Tag(new Dictionary { { key, string.Empty } }, null), null); - GetTagResource().Update(WaitUntil.Completed, tagPatch, cancellationToken: cancellationToken); - var originalResponse = _resourcesRestClient.GetById(Id, apiVersion, cancellationToken); - return Response.FromValue(new GenericResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// RequestPath: /{resourceId} - /// ContextualPath: /{resourceId} - /// OperationId: Resources_UpdateById - /// Updates a resource by ID. - /// "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Update resource parameters. - /// The cancellation token to use. - /// is null. - public async virtual Task> UpdateAsync(WaitUntil waitUntil, GenericResourceData data, CancellationToken cancellationToken = default) - { - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResource.Update"); - scope.Start(); - try - { - var apiVersion = await GetApiVersionAsync(cancellationToken).ConfigureAwait(false); - var response = await _resourcesRestClient.UpdateByIdAsync(Id, apiVersion, data, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(new GenericResourceOperationSource(Client), _clientDiagnostics, Pipeline, _resourcesRestClient.CreateUpdateByIdRequest(Id, apiVersion, data).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// RequestPath: /{resourceId} - /// ContextualPath: /{resourceId} - /// OperationId: Resources_UpdateById - /// Updates a resource by ID. - /// "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Update resource parameters. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation Update(WaitUntil waitUntil, GenericResourceData data, CancellationToken cancellationToken = default) - { - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResource.Update"); - scope.Start(); - try - { - var apiVersion = GetApiVersion(cancellationToken); - var response = _resourcesRestClient.UpdateById(Id, apiVersion, data, cancellationToken); - var operation = new ResourcesArmOperation(new GenericResourceOperationSource(Client), _clientDiagnostics, Pipeline, _resourcesRestClient.CreateUpdateByIdRequest(Id, apiVersion, data).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - private string GetApiVersion(CancellationToken cancellationToken) - { - string version = _providerCollection.GetApiVersion(Id.ResourceType, cancellationToken); - if (version is null) - { - throw new InvalidOperationException($"An invalid resource id was given {Id}"); - } - return version; - } - - private async Task GetApiVersionAsync(CancellationToken cancellationToken) - { - string version = await _providerCollection.GetApiVersionAsync(Id.ResourceType, cancellationToken).ConfigureAwait(false); - if (version is null) - { - throw new InvalidOperationException($"An invalid resource id was given {Id}"); - } - return version; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/GenericResourceCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/GenericResourceCollection.cs deleted file mode 100644 index ee0a0f75a1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/GenericResourceCollection.cs +++ /dev/null @@ -1,266 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -[assembly: CodeGenSuppressType("GenericResourceCollection")] -namespace Azure.ResourceManager.Resources -{ - /// A class representing collection of GenericResource and their operations over its parent. - public partial class GenericResourceCollection : ArmCollection - { - private readonly ClientDiagnostics _clientDiagnostics; - private readonly ResourcesRestOperations _resourcesRestClient; - - /// Initializes a new instance of the class for mocking. - protected GenericResourceCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal GenericResourceCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _clientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ProviderConstants.DefaultProviderNamespace, Diagnostics); - _resourcesRestClient = new ResourcesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint); - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != TenantResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, TenantResource.ResourceType), nameof(id)); - } - - // Collection level operations. - - /// RequestPath: /{resourceId} - /// ContextualPath: / - /// OperationId: Resources_CreateOrUpdateById - /// Create a resource by ID. - /// "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// Create or update resource parameters. - /// The cancellation token to use. - /// or is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, ResourceIdentifier resourceId, GenericResourceData data, CancellationToken cancellationToken = default) - { - if (resourceId == null) - { - throw new ArgumentNullException(nameof(resourceId)); - } - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResourceCollection.CreateOrUpdate"); - scope.Start(); - try - { - var apiVersion = GetApiVersion(new ResourceIdentifier(resourceId), cancellationToken); - var response = _resourcesRestClient.CreateOrUpdateById(resourceId, apiVersion, data, cancellationToken); - var operation = new ResourcesArmOperation(new GenericResourceOperationSource(Client), _clientDiagnostics, Pipeline, _resourcesRestClient.CreateCreateOrUpdateByIdRequest(resourceId, apiVersion, data).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// RequestPath: /{resourceId} - /// ContextualPath: / - /// OperationId: Resources_CreateOrUpdateById - /// Create a resource by ID. - /// "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// Create or update resource parameters. - /// The cancellation token to use. - /// , or is null. - public async virtual Task> CreateOrUpdateAsync(WaitUntil waitUntil, ResourceIdentifier resourceId, GenericResourceData data, CancellationToken cancellationToken = default) - { - if (resourceId == null) - { - throw new ArgumentNullException(nameof(resourceId)); - } - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResourceCollection.CreateOrUpdate"); - scope.Start(); - try - { - var apiVersion = await GetApiVersionAsync(new ResourceIdentifier(resourceId), cancellationToken).ConfigureAwait(false); - var response = await _resourcesRestClient.CreateOrUpdateByIdAsync(resourceId, apiVersion, data, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(new GenericResourceOperationSource(Client), _clientDiagnostics, Pipeline, _resourcesRestClient.CreateCreateOrUpdateByIdRequest(resourceId, apiVersion, data).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// RequestPath: /{resourceId} - /// ContextualPath: / - /// OperationId: Resources_GetById - /// Gets a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The cancellation token to use. - /// is null. - public virtual Response Get(ResourceIdentifier resourceId, CancellationToken cancellationToken = default) - { - if (resourceId == null) - { - throw new ArgumentNullException(nameof(resourceId)); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResourceCollection.Get"); - scope.Start(); - try - { - var apiVersion = GetApiVersion(new ResourceIdentifier(resourceId), cancellationToken); - var response = _resourcesRestClient.GetById(resourceId, apiVersion, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new GenericResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// RequestPath: /{resourceId} - /// ContextualPath: / - /// OperationId: Resources_GetById - /// Gets a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The cancellation token to use. - /// is null. - public async virtual Task> GetAsync(ResourceIdentifier resourceId, CancellationToken cancellationToken = default) - { - if (resourceId == null) - { - throw new ArgumentNullException(nameof(resourceId)); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResourceCollection.Get"); - scope.Start(); - try - { - var apiVersion = await GetApiVersionAsync(new ResourceIdentifier(resourceId), cancellationToken).ConfigureAwait(false); - var response = await _resourcesRestClient.GetByIdAsync(resourceId, apiVersion, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new GenericResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Tries to get details for this resource from the service. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The cancellation token to use. - /// is null. - public virtual Response Exists(ResourceIdentifier resourceId, CancellationToken cancellationToken = default) - { - if (resourceId == null) - { - throw new ArgumentNullException(nameof(resourceId)); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResourceCollection.Exists"); - scope.Start(); - try - { - var apiVersion = GetApiVersion(new ResourceIdentifier(resourceId), cancellationToken); - var response = _resourcesRestClient.GetById(resourceId, apiVersion, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Tries to get details for this resource from the service. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The cancellation token to use. - /// is null. - public async virtual Task> ExistsAsync(ResourceIdentifier resourceId, CancellationToken cancellationToken = default) - { - if (resourceId == null) - { - throw new ArgumentNullException(nameof(resourceId)); - } - - using var scope = _clientDiagnostics.CreateScope("GenericResourceCollection.Exists"); - scope.Start(); - try - { - var apiVersion = await GetApiVersionAsync(new ResourceIdentifier(resourceId), cancellationToken).ConfigureAwait(false); - var response = await _resourcesRestClient.GetByIdAsync(resourceId, apiVersion, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - private string GetApiVersion(ResourceIdentifier resourceId, CancellationToken cancellationToken) - { - ResourceIdentifier subscription = resourceId.GetSubscriptionResourceIdentifier(); - if (subscription == null) - { - throw new ArgumentException("Only resource id in a subscription is supported", nameof(resourceId)); - } - ResourceProviderCollection collection = new ResourceProviderCollection(Client, subscription); - string version = collection.GetApiVersion(resourceId.ResourceType, cancellationToken); - if (version is null) - { - throw new InvalidOperationException($"An invalid resource id was given {resourceId}"); - } - return version; - } - - private async Task GetApiVersionAsync(ResourceIdentifier resourceId, CancellationToken cancellationToken) - { - ResourceIdentifier subscription = resourceId.GetSubscriptionResourceIdentifier(); - if (subscription == null) - { - throw new ArgumentException("Only resource id in a subscription is supported", nameof(resourceId)); - } - ResourceProviderCollection collection = new ResourceProviderCollection(Client, subscription); - string version = await collection.GetApiVersionAsync(resourceId.ResourceType, cancellationToken).ConfigureAwait(false); - if (version is null) - { - throw new InvalidOperationException($"An invalid resource id was given {resourceId}"); - } - return version; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/GenericResourceData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/GenericResourceData.cs deleted file mode 100644 index f2bf593f62..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/GenericResourceData.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - // this piece of customization code is used for fixing the base class here - public partial class GenericResourceData : TrackedResourceExtendedData - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/HelperSuppressions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/HelperSuppressions.cs deleted file mode 100644 index f7cda07595..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/HelperSuppressions.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using Azure.Core; - -[assembly: CodeGenSuppressType("Azure.ResourceManager.Optional")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.ChangeTrackingList")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.RequestContentHelper")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.Argument")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.ChangeTrackingDictionary")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.ModelSerializationExtensions")] -[assembly: CodeGenSuppressType("Azure.ResourceManager.BicepSerializationHelpers")] diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApi.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApi.Serialization.cs deleted file mode 100644 index af88ab9534..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApi.Serialization.cs +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ArmRestApi : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmRestApi)} does not support '{format}' format."); - } - - writer.WriteStartObject(); - if (format != "W" && Optional.IsDefined(Origin)) - { - writer.WritePropertyName("origin"u8); - writer.WriteStringValue(Origin); - } - if (format != "W" && Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - writer.WritePropertyName("display"u8); - writer.WriteStartObject(); - if (format != "W" && Optional.IsDefined(Operation)) - { - writer.WritePropertyName("operation"u8); - writer.WriteStringValue(Operation); - } - if (format != "W" && Optional.IsDefined(Resource)) - { - writer.WritePropertyName("resource"u8); - writer.WriteStringValue(Resource); - } - if (format != "W" && Optional.IsDefined(Description)) - { - writer.WritePropertyName("description"u8); - writer.WriteStringValue(Description); - } - if (format != "W" && Optional.IsDefined(Provider)) - { - writer.WritePropertyName("provider"u8); - writer.WriteStringValue(Provider); - } - writer.WriteEndObject(); - writer.WriteEndObject(); - } - - ArmRestApi IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmRestApi)} does not support '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeArmRestApi(document.RootElement, options); - } - - internal static ArmRestApi DeserializeArmRestApi(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= new ModelReaderWriterOptions("W"); - - string origin = default; - string name = default; - string operation = default; - string resource = default; - string description = default; - string provider = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("origin")) - { - origin = property.Value.GetString(); - continue; - } - if (property.NameEquals("name")) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("display")) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("operation")) - { - operation = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("resource")) - { - resource = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("description")) - { - description = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("provider")) - { - provider = property0.Value.GetString(); - continue; - } - } - continue; - } - } - return new ArmRestApi(origin, name, operation, resource, description, provider); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ArmRestApi)} does not support '{options.Format}' format."); - } - } - - ArmRestApi IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeArmRestApi(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ArmRestApi)} does not support '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApi.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApi.cs deleted file mode 100644 index 164b744651..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApi.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Describes the properties of an Operation value. - public partial class ArmRestApi - { - /// Initializes a new instance of RestApi for mocking. - internal ArmRestApi() - { - } - - /// Initializes a new instance of RestApi. - /// The origin of the operation. - /// The name of the operation. - /// The display name of the operation. - /// The display name of the resource the operation applies to. - /// The description of the operation. - /// The resource provider for the operation. - internal ArmRestApi(string origin, string name, string operation, string resource, string description, string provider) - { - Origin = origin; - Name = name; - Operation = operation; - Resource = resource; - Description = description; - Provider = provider; - } - - /// The origin of the operation. - public string Origin { get; } - /// The name of the operation. - public string Name { get; } - /// The display name of the operation. - public string Operation { get; } - /// The display name of the resource the operation applies to. - public string Resource { get; } - /// The description of the operation. - public string Description { get; } - /// The resource provider for the operation. - public string Provider { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApiListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApiListResult.Serialization.cs deleted file mode 100644 index ab24d2f204..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApiListResult.Serialization.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class ArmRestApiListResult - { - internal static ArmRestApiListResult DeserializeComputeOperationListResult(JsonElement element) - { - IReadOnlyList value = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value")) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ArmRestApi.DeserializeArmRestApi(item)); - } - value = array; - continue; - } - } - return new ArmRestApiListResult(value ?? new ChangeTrackingList()); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApiListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApiListResult.cs deleted file mode 100644 index 884cd877eb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApiListResult.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The List Operation operation response. - internal partial class ArmRestApiListResult - { - /// Initializes a new instance of RestApiListResult. - internal ArmRestApiListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of RestApiListResult. - /// The list of operations. - internal ArmRestApiListResult(IReadOnlyList value) - { - Value = value; - } - - /// The list of operations. - public IReadOnlyList Value { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/EnforcementMode.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/EnforcementMode.cs deleted file mode 100644 index ccb5c3feb6..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/EnforcementMode.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The policy assignment enforcement mode. Possible values are Default and DoNotEnforce. - public readonly partial struct EnforcementMode : IEquatable - { - private const string EnforcedValue = "Default"; - - /// The policy effect is enforced during resource creation or update. - [EditorBrowsable(EditorBrowsableState.Never)] - public static EnforcementMode Enforced { get; } = new EnforcementMode(EnforcedValue); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/LocationExpanded.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/LocationExpanded.cs deleted file mode 100644 index e585737abe..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/LocationExpanded.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.Collections.Generic; -using Azure.Core; - -[assembly:CodeGenSuppressType("CreatedByType")] -[assembly:CodeGenSuppressType("PolicyAssignmentIdentityType")] -[assembly:CodeGenSuppressType("PolicyAssignmentIdentityTypeExtensions")] -[assembly:CodeGenSuppressType("CloudError")] -namespace Azure.ResourceManager.Resources.Models -{ - public partial class LocationExpanded - { - /// - /// Convert LocationExpanded into a Location object. - /// - /// The location to convert. - public static implicit operator AzureLocation(LocationExpanded location) - { - return new AzureLocation(location.Name, location.DisplayName); - } - - /// Initializes a new instance of LocationExpanded. - /// The fully qualified ID of the location. For example, /subscriptions/00000000-0000-0000-0000-000000000000/locations/westus. - /// The subscription ID. - /// The location name. - /// The location type. - /// The display name of the location. - /// The display name of the location and its region. - /// Metadata of the location, such as lat/long, paired region, and others. - /// The availability zone mappings for this region. - internal LocationExpanded(string id, string subscriptionId, string name, LocationType? locationType, string displayName, string regionalDisplayName, LocationMetadata metadata, IReadOnlyList availabilityZoneMappings) - { - Id = id; - ResourceIdentifier subId = new ResourceIdentifier(id); - SubscriptionId = subscriptionId ?? subId.SubscriptionId; - Name = name; - LocationType = locationType; - DisplayName = displayName; - RegionalDisplayName = regionalDisplayName; - Metadata = metadata; - AvailabilityZoneMappings = availabilityZoneMappings; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/LocationMetadata.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/LocationMetadata.cs deleted file mode 100644 index f266b21d35..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/LocationMetadata.cs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System.ClientModel.Primitives; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - [CodeGenSerialization(nameof(Longitude), SerializationValueHook = nameof(WriteLongitude), DeserializationValueHook = nameof(ReadLongitude))] - [CodeGenSerialization(nameof(Latitude), SerializationValueHook = nameof(WriteLatitude), DeserializationValueHook = nameof(ReadLatitude))] - public partial class LocationMetadata - { - /// The longitude of the location. - public double? Longitude { get; } - /// The latitude of the location. - public double? Latitude { get; } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void WriteLongitude(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - if (Longitude.HasValue) - { - writer.WriteStringValue(Longitude.Value.ToString(CultureInfo.InvariantCulture)); - } - else - { - writer.WriteNullValue(); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static void ReadLongitude(JsonProperty property, ref double? longitude) - { - if (property.Value.ValueKind == JsonValueKind.Null) - return; - - longitude = double.Parse(property.Value.GetString(), CultureInfo.InvariantCulture); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void WriteLatitude(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - if (Latitude.HasValue) - { - writer.WriteStringValue(Latitude.Value.ToString(CultureInfo.InvariantCulture)); - } - else - { - writer.WriteNullValue(); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static void ReadLatitude(JsonProperty property, ref double? latitude) - { - if (property.Value.ValueKind == JsonValueKind.Null) - return; - - latitude = double.Parse(property.Value.GetString(), CultureInfo.InvariantCulture); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ResourcesMoveContent.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ResourcesMoveContent.cs deleted file mode 100644 index c63ec6232d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ResourcesMoveContent.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System.ComponentModel; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourcesMoveContent - { - /// The target resource group. - [EditorBrowsable(EditorBrowsableState.Never)] - public string TargetResourceGroup { get => TargetResourceGroupId.ToString(); set => TargetResourceGroupId = new ResourceIdentifier(value); } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ResourcesSku.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ResourcesSku.cs deleted file mode 100644 index 41b1f3e925..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/ResourcesSku.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - [CodeGenType("ResourceManagerSku")] - public partial class ResourcesSku - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/SubResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/SubResource.Serialization.cs deleted file mode 100644 index c6c9a86519..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/SubResource.Serialization.cs +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - [JsonConverter(typeof(SubResourceConverter))] - public partial class SubResource : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, new ModelReaderWriterOptions("W")); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SubResource)} does not support '{format}' format."); - } - - writer.WriteStartObject(); - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - writer.WriteEndObject(); - } - - SubResource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SubResource)} does not support '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeSubResource(document.RootElement, options); - } - - internal static SubResource DeserializeSubResource(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= new ModelReaderWriterOptions("W"); - - ResourceIdentifier id = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id")) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - } - return new SubResource(id); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(SubResource)} does not support '{options.Format}' format."); - } - } - - SubResource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeSubResource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(SubResource)} does not support '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class SubResourceConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, SubResource model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model); - } - public override SubResource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeSubResource(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/SubResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/SubResource.cs deleted file mode 100644 index 4677811ac4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/SubResource.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// - /// A class representing a sub-resource that contains only the read-only ID. - /// - [PropertyReferenceType] - public partial class SubResource - { - /// - /// Initializes an empty instance of for mocking. - /// - [InitializationConstructor] - public SubResource() - { - } - - /// Initializes a new instance of . - /// ARM resource Id. - [SerializationConstructor] - protected internal SubResource(ResourceIdentifier id) - { - Id = id; - } - - /// - /// Gets the ARM resource identifier. - /// - /// - public virtual ResourceIdentifier Id { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/Tag.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/Tag.cs deleted file mode 100644 index de31694444..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/Tag.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// A dictionary of name and value pairs. - public partial class Tag - { - /// Dictionary of <string>. - [CodeGenMember("Tags")] - public IDictionary TagValues { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/WritableSubResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/WritableSubResource.Serialization.cs deleted file mode 100644 index b44b3de3e9..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/WritableSubResource.Serialization.cs +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// - /// A class representing a sub-resource that contains only the ID. - /// - [JsonConverter(typeof(WritableSubResourceConverter))] - public partial class WritableSubResource : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, new ModelReaderWriterOptions("W")); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(WritableSubResource)} does not support '{format}' format."); - } - - writer.WriteStartObject(); - if (Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"); - writer.WriteStringValue(Id); - } - writer.WriteEndObject(); - } - - WritableSubResource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(WritableSubResource)} does not support '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeWritableSubResource(document.RootElement, options); - } - - /// - /// Deserialize the input JSON element to a WritableSubResource object. - /// - /// The JSON element to be deserialized. - /// The options to use. - /// Deserialized WritableSubResource object. - internal static WritableSubResource DeserializeWritableSubResource(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= new ModelReaderWriterOptions("W"); - - ResourceIdentifier id = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id")) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - } - return new WritableSubResource(id); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(WritableSubResource)} does not support '{options.Format}' format."); - } - } - - WritableSubResource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data); - return DeserializeWritableSubResource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(WritableSubResource)} does not support '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class WritableSubResourceConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, WritableSubResource model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model); - } - public override WritableSubResource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeWritableSubResource(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/WritableSubResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/WritableSubResource.cs deleted file mode 100644 index 105741ada8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/Models/WritableSubResource.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// - /// A class representing a sub-resource that contains only the ID. - /// - [PropertyReferenceType] - public partial class WritableSubResource - { - /// - /// Initializes an empty instance of for mocking. - /// - [InitializationConstructor] - public WritableSubResource() - { - } - - /// Initializes a new instance of . - /// ARM resource Id. - [SerializationConstructor] - protected internal WritableSubResource(ResourceIdentifier id) - { - Id = id; - } - - /// - /// Gets or sets the ARM resource identifier. - /// - /// - public ResourceIdentifier Id { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/PolicyAssignmentData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/PolicyAssignmentData.cs deleted file mode 100644 index 0889491a1a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/PolicyAssignmentData.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.ComponentModel; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// A class representing the PolicyAssignment data model. - public partial class PolicyAssignmentData : ResourceData - { -#pragma warning disable CS0618 // This type is obsolete and will be removed in a future release. - private SystemAssignedServiceIdentity _identity; - /// The managed identity associated with the policy assignment. - [Obsolete("This property is obsolete and will be removed in a future release. Please use ManagedIdentity.", false)] - [EditorBrowsable(EditorBrowsableState.Never)] - public SystemAssignedServiceIdentity Identity - { - get - { - if (ManagedIdentity != null) - { - if (_identity == null || _identity.Identity != ManagedIdentity) - { - _identity = new SystemAssignedServiceIdentity(ManagedIdentity); - } - } - else - { - _identity = null; - } - return _identity; - } - set - { - _identity = value; - ManagedIdentity = value == null ? null : _identity.Identity; - } - } -#pragma warning restore CS0618 // This type is obsolete and will be removed in a future release. - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/PolicyAssignmentResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/PolicyAssignmentResource.cs deleted file mode 100644 index b658d222e0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/PolicyAssignmentResource.cs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class PolicyAssignmentResource - { - /// - /// This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Create - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Parameters for the policy assignment. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(WaitUntil waitUntil, PolicyAssignmentData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentResource.Update"); - scope.Start(); - try - { - var response = await _policyAssignmentRestClient.CreateAsync(Id.Parent, Id.Name, data, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(Response.FromValue(new PolicyAssignmentResource(Client, response), response.GetRawResponse())); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Create - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Parameters for the policy assignment. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation Update(WaitUntil waitUntil, PolicyAssignmentData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentResource.Update"); - scope.Start(); - try - { - var response = _policyAssignmentRestClient.Create(Id.Parent, Id.Name, data, cancellationToken); - var operation = new ResourcesArmOperation(Response.FromValue(new PolicyAssignmentResource(Client, response), response.GetRawResponse())); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceGroupBuilder.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceGroupBuilder.cs deleted file mode 100644 index 22cc3f1726..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceGroupBuilder.cs +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a builder object used to create Azure resources. - /// - internal class ResourceGroupBuilder - { - /// - /// Initializes a new instance of the class. - /// - /// The collection object to create the resource in. - /// The resource to create. - public ResourceGroupBuilder(ResourceGroupCollection collection, ResourceGroupData resource) - { - Resource = resource; - Collection = collection; - } - - /// - /// Gets the resource object to create. - /// - protected ResourceGroupData Resource { get; private set; } - - /// - /// Gets the resource name. - /// - protected string ResourceName { get; private set; } - - /// - /// Gets the collection object to create the resource in. - /// - protected ResourceGroupCollection Collection { get; private set; } - - /// - /// Creates the resource object to send to the Azure API. - /// - /// The resource to create. - public ResourceGroupData Build() - { - ThrowIfNotValid(); - OnBeforeBuild(); - InternalBuild(); - OnAfterBuild(); - - return Resource; - } - - /// - /// The operation to create or update a resource. Please note some properties can be set only during creation. - /// - /// The name of the new resource to create. - /// Waits for the completion of the long running operations. - /// A token to allow the caller to cancel the call to the service. The default value is . - /// A response with the operation for this resource. - /// Name cannot be null or a whitespace. - public ArmOperation CreateOrUpdate(string name, WaitUntil waitUntil = WaitUntil.Completed, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(name)) - throw new ArgumentException("Name cannot be null or whitespace.", nameof(name)); - - ResourceName = name; - Resource = Build(); - - return Collection.CreateOrUpdate(waitUntil, name, Resource, cancellationToken); - } - - /// - /// The operation to create or update a resource. Please note some properties can be set only during creation. - /// - /// The name of the new resource to create. - /// Waits for the completion of the long running operations. - /// A token to allow the caller to cancel the call to the service. The default value is . - /// A that on completion returns a response with the operation for this resource. - /// Name cannot be null or a whitespace. - public async Task> CreateOrUpdateAsync(string name, WaitUntil waitUntil = WaitUntil.Completed, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(name)) - throw new ArgumentException("Name cannot be null or whitespace.", nameof(name)); - - ResourceName = name; - Resource = Build(); - - return await Collection.CreateOrUpdateAsync(waitUntil, name, Resource, cancellationToken).ConfigureAwait(false); - } - - /// - /// Determines whether or not the resource is valid. - /// - /// The message indicating what is wrong with the resource. - /// Whether or not the resource is valid. - protected virtual bool IsValid(out string message) - { - message = string.Empty; - - return true; - } - - /// - /// Perform any tasks necessary after the resource is built. - /// - protected virtual void OnAfterBuild() - { - } - - /// - /// Perform any tasks necessary before the resource is built. - /// - protected virtual void OnBeforeBuild() - { - } - - private static void InternalBuild() - { - } - - private void ThrowIfNotValid() - { - if (!IsValid(out var message)) - { - throw new InvalidOperationException(message); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceGroupCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceGroupCollection.cs deleted file mode 100644 index cf7e8bb395..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceGroupCollection.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Threading; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// A class representing collection of ResourceGroupResource and their operations over its parent. - [CodeGenSuppress("GetAllAsGenericResources", typeof(string), typeof(string), typeof(int?), typeof(CancellationToken))] - [CodeGenSuppress("GetAllAsGenericResourcesAsync", typeof(string), typeof(string), typeof(int?), typeof(CancellationToken))] - public partial class ResourceGroupCollection : ArmCollection, IEnumerable, IAsyncEnumerable - - { - /// - /// Constructs an object used to create a resource group. - /// - /// The location of the resource group. - /// The tags of the resource group. - /// Who the resource group is managed by. - /// A builder with and . - /// Location cannot be null. - internal ResourceGroupBuilder Construct(AzureLocation location, IDictionary tags = default, string managedBy = default) - { - var model = new ResourceGroupData(location); - if (!(tags is null)) - model.Tags.ReplaceWith(tags); - model.ManagedBy = managedBy; - return new ResourceGroupBuilder(this, model); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceGroupResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceGroupResource.cs deleted file mode 100644 index 75c02571f4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceGroupResource.cs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -[assembly:CodeGenSuppressType("ResourceGroupUpdateOperation")] -namespace Azure.ResourceManager.Resources -{ - /// A Class representing a ResourceGroupResource along with the instance operations that can be performed on it. - public partial class ResourceGroupResource : ArmResource - { - /// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/resources - /// ContextualPath: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// OperationId: Resources_ListByResourceGroup - /// Get all the resources for a resource group. - /// The filter to apply on the operation.<br><br>The properties you can use for eq (equals) or ne (not equals) are: location, resourceType, name, resourceGroup, identity, identity/principalId, plan, plan/publisher, plan/product, plan/name, plan/version, and plan/promotionCode.<br><br>For example, to filter by a resource type, use: $filter=resourceType eq 'Microsoft.Network/virtualNetworks'<br><br>You can use substringof(value, property) in the filter. The properties you can use for substring are: name and resourceGroup.<br><br>For example, to get all resources with 'demo' anywhere in the name, use: $filter=substringof('demo', name)<br><br>You can link more than one substringof together by adding and/or operators.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. When you filter by a tag name and value, the tags for each resource are not returned in the results.<br><br>You can use some properties together when filtering. The combinations you can use are: substringof and/or resourceType, plan and plan/publisher and plan/name, identity and identity/principalId. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of results to return. If null is passed, returns all resources. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetGenericResourcesAsync(string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - async Task> FirstPageFunc(int? pageSizeHint) - { - using var scope = _resourceGroupResourcesClientDiagnostics.CreateScope("ResourceGroupResource.GetGenericResources"); - scope.Start(); - try - { - var response = await _resourceGroupResourcesRestClient.ListByResourceGroupAsync(Id.SubscriptionId, Id.ResourceGroupName, filter, expand, top, cancellationToken: cancellationToken).ConfigureAwait(false); - return Page.FromValues(response.Value.Value.Select(value => new GenericResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - async Task> NextPageFunc(string nextLink, int? pageSizeHint) - { - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.GetGenericResources"); - scope.Start(); - try - { - var response = await _resourceGroupResourcesRestClient.ListByResourceGroupNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, filter, expand, top, cancellationToken: cancellationToken).ConfigureAwait(false); - return Page.FromValues(response.Value.Value.Select(value => new GenericResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); - } - - /// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/resources - /// ContextualPath: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// OperationId: Resources_ListByResourceGroup - /// Get all the resources for a resource group. - /// The filter to apply on the operation.<br><br>The properties you can use for eq (equals) or ne (not equals) are: location, resourceType, name, resourceGroup, identity, identity/principalId, plan, plan/publisher, plan/product, plan/name, plan/version, and plan/promotionCode.<br><br>For example, to filter by a resource type, use: $filter=resourceType eq 'Microsoft.Network/virtualNetworks'<br><br>You can use substringof(value, property) in the filter. The properties you can use for substring are: name and resourceGroup.<br><br>For example, to get all resources with 'demo' anywhere in the name, use: $filter=substringof('demo', name)<br><br>You can link more than one substringof together by adding and/or operators.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. When you filter by a tag name and value, the tags for each resource are not returned in the results.<br><br>You can use some properties together when filtering. The combinations you can use are: substringof and/or resourceType, plan and plan/publisher and plan/name, identity and identity/principalId. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of results to return. If null is passed, returns all resources. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetGenericResources(string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Page FirstPageFunc(int? pageSizeHint) - { - using var scope = _resourceGroupResourcesClientDiagnostics.CreateScope("ResourceGroupResource.GetGenericResources"); - scope.Start(); - try - { - var response = _resourceGroupResourcesRestClient.ListByResourceGroup(Id.SubscriptionId, Id.ResourceGroupName, filter, expand, top, cancellationToken: cancellationToken); - return Page.FromValues(response.Value.Value.Select(value => new GenericResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - Page NextPageFunc(string nextLink, int? pageSizeHint) - { - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.GetGenericResources"); - scope.Start(); - try - { - var response = _resourceGroupResourcesRestClient.ListByResourceGroupNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, filter, expand, top, cancellationToken: cancellationToken); - return Page.FromValues(response.Value.Value.Select(value => new GenericResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceManagerModelFactory.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceManagerModelFactory.cs deleted file mode 100644 index 73d3cdd844..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceManagerModelFactory.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Models -{ - /// Model factory for read-only models. - public static partial class ResourceManagerModelFactory - { - /// Initializes a new instance of SubResource. - /// - /// A new instance for mocking. - public static SubResource SubResource(ResourceIdentifier id = null) - { - return new SubResource(id); - } - - /// Initializes a new instance of WritableSubResource. - /// - /// A new instance for mocking. - public static WritableSubResource WritableSubResource(ResourceIdentifier id = null) - { - return new WritableSubResource(id); - } - - /// Initializes a new instance of LocationExpanded. - /// The fully qualified ID of the location. For example, /subscriptions/00000000-0000-0000-0000-000000000000/locations/westus. - /// The subscription ID. - /// The location name. - /// The location type. - /// The display name of the location. - /// The display name of the location and its region. - /// Metadata of the location, such as lat/long, paired region, and others. - /// A new instance for mocking. - public static LocationExpanded LocationExpanded(string id, string subscriptionId, string name, LocationType? locationType, string displayName, string regionalDisplayName, LocationMetadata metadata) - { - return new LocationExpanded(id, subscriptionId, name, locationType, displayName, regionalDisplayName, metadata, null); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceProviderCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceProviderCollection.cs deleted file mode 100644 index c883e46b6d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceProviderCollection.cs +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// A class representing collection of Provider and their operations over its parent. - [CodeGenSuppress("GetAllAsGenericResources", typeof(string), typeof(string), typeof(int?), typeof(CancellationToken))] - [CodeGenSuppress("GetAllAsGenericResourcesAsync", typeof(string), typeof(string), typeof(int?), typeof(CancellationToken))] - public partial class ResourceProviderCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - /// Initializes a new instance of the class. - /// The resource representing the parent resource. - internal ResourceProviderCollection(ArmResource parent) : this(parent.Client, parent.Id) - { - } - - internal ResourceProviderCollection(ArmClient client, ResourceIdentifier id) - : base(client, id) - { - _resourceProviderProvidersClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceProviderResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceProviderResource.ResourceType, out string providerApiVersion); - _resourceProviderProvidersRestClient = new ProvidersRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, providerApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - [ForwardsClientCalls(true)] - internal virtual string GetApiVersion(ResourceType resourceType, CancellationToken cancellationToken = default) - { - string version; - Dictionary resourceVersions; - if (!Client.ApiVersionOverrides.TryGetValue(resourceType, out version)) - { - if (!Client.ResourceApiVersionCache.TryGetValue(resourceType.Namespace, out resourceVersions)) - { - resourceVersions = LoadResourceVersionsFromApi(resourceType.Namespace, cancellationToken); - Client.ResourceApiVersionCache.TryAdd(resourceType.Namespace, resourceVersions); - } - if (!resourceVersions.TryGetValue(resourceType.Type, out version)) - { - throw new InvalidOperationException($"Invalid resource type {resourceType}"); - } - } - return version; - } - - [ForwardsClientCalls(true)] - internal virtual async ValueTask GetApiVersionAsync(ResourceType resourceType, CancellationToken cancellationToken = default) - { - string version; - Dictionary resourceVersions; - if (!Client.ApiVersionOverrides.TryGetValue(resourceType, out version)) - { - if (!Client.ResourceApiVersionCache.TryGetValue(resourceType.Namespace, out resourceVersions)) - { - resourceVersions = await LoadResourceVersionsFromApiAsync(resourceType.Namespace, cancellationToken).ConfigureAwait(false); - Client.ResourceApiVersionCache.TryAdd(resourceType.Namespace, resourceVersions); - } - if (!resourceVersions.TryGetValue(resourceType.Type, out version)) - { - throw new InvalidOperationException($"Invalid resource type {resourceType}"); - } - } - return version; - } - - private Dictionary LoadResourceVersionsFromApi(string resourceNamespace, CancellationToken cancellationToken = default) - { - ResourceProviderResource results = Get(resourceNamespace, cancellationToken: cancellationToken); - return GetVersionsFromResult(results); - } - - private async Task> LoadResourceVersionsFromApiAsync(string resourceNamespace, CancellationToken cancellationToken = default) - { - ResourceProviderResource results = await GetAsync(resourceNamespace, cancellationToken: cancellationToken).ConfigureAwait(false); - return GetVersionsFromResult(results); - } - - private static Dictionary GetVersionsFromResult(ResourceProviderResource results) - { - Dictionary resourceVersions = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (var type in results.Data.ResourceTypes) - { - if (type.ApiVersions.Count == 0) - continue; - resourceVersions[type.ResourceType] = type.ApiVersions[0]; - } - return resourceVersions; - } - - /// - /// Gets all resource providers for a subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers - /// - /// - /// Operation Id - /// Providers_List - /// - /// - /// - /// [This parameter is no longer supported.] The number of results to return. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("This method is obsolete as the `top` parameter is not supported by service and will be removed in a future release.", false)] - public virtual AsyncPageable GetAllAsync(int? top, string expand, CancellationToken cancellationToken = default) - { - return GetAllAsync(expand, cancellationToken); - } - - /// - /// Gets all resource providers for a subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers - /// - /// - /// Operation Id - /// Providers_List - /// - /// - /// - /// [This parameter is no longer supported.] The number of results to return. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("This method is obsolete as the `top` parameter is not supported by service and will be removed in a future release.", false)] - public virtual Pageable GetAll(int? top, string expand, CancellationToken cancellationToken = default) - { - return GetAll(expand, cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceProviderData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceProviderData.cs deleted file mode 100644 index 7081df7c19..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceProviderData.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// A class representing the Provider data model. - [PropertyReferenceType] - [JsonConverter(typeof(ProviderDataConverter))] - public partial class ResourceProviderData - { - /// Initializes a new instance of ProviderData. - [InitializationConstructor] - public ResourceProviderData() - { - ResourceTypes = new ChangeTrackingList(); - } - - /// Initializes a new instance of ProviderData. - /// The provider ID. - /// The namespace of the resource provider. - /// The registration state of the resource provider. - /// The registration policy of the resource provider. - /// The collection of provider resource types. - /// The provider authorization consent state. - [SerializationConstructor] - internal ResourceProviderData(ResourceIdentifier id, string @namespace, string registrationState, string registrationPolicy, IReadOnlyList resourceTypes, ProviderAuthorizationConsentState? providerAuthorizationConsentState) - { - Id = id; - Namespace = @namespace; - RegistrationState = registrationState; - RegistrationPolicy = registrationPolicy; - ResourceTypes = resourceTypes; - ProviderAuthorizationConsentState = providerAuthorizationConsentState; - } - - /// The provider ID. - public ResourceIdentifier Id { get; } - - internal partial class ProviderDataConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, ResourceProviderData providerData, JsonSerializerOptions options) - { - writer.WriteObjectValue(providerData); - } - public override ResourceProviderData Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceProviderData(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceProviderResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceProviderResource.cs deleted file mode 100644 index d31340bbca..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/ResourceProviderResource.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Threading; -using Azure.Core; - -namespace Azure.ResourceManager.Resources -{ - /// A Class representing a Provider along with the instance operations that can be performed on it. - [CodeGenSuppress("GetAvailableLocations", typeof(CancellationToken))] - [CodeGenSuppress("GetAvailableLocationsAsync", typeof(CancellationToken))] - public partial class ResourceProviderResource : ArmResource - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/RestOperations/RestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/RestOperations/RestOperations.cs deleted file mode 100644 index 9652d2393f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/RestOperations/RestOperations.cs +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class RestOperations - { - private Uri endpoint; - private string apiVersion; - private ClientDiagnostics _clientDiagnostics; - private HttpPipeline _pipeline; - private string _nameSpace; - private readonly TelemetryDetails _userAgent; - - /// Initializes a new instance of RestOperations. - /// The namespace to get the operations for. - /// The handler for diagnostic messaging in the client. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The client options used to construct the current client. - /// server parameter. - /// Api Version. - /// is null. - public RestOperations(string nameSpace, string apiVersion, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string applicationId, Uri endpoint = null) - { - endpoint ??= new Uri("https://management.azure.com"); - if (apiVersion == null) - { - throw new ArgumentNullException(nameof(apiVersion)); - } - - this.endpoint = endpoint; - this.apiVersion = apiVersion; - _clientDiagnostics = clientDiagnostics; - _pipeline = pipeline; - _nameSpace = nameSpace; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal HttpMessage CreateListRequest() - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(endpoint); - uri.AppendPath($"/providers/{_nameSpace}/operations", false); - uri.AppendQuery("api-version", apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets a list of operations. - /// The cancellation token to use. - public async Task> ListAsync(CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ArmRestApiListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); - value = ArmRestApiListResult.DeserializeComputeOperationListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets a list of operations. - /// The cancellation token to use. - public Response List(CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ArmRestApiListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream); - value = ArmRestApiListResult.DeserializeComputeOperationListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/RestOperations/TenantsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/RestOperations/TenantsRestOperations.cs deleted file mode 100644 index a04a4128ac..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/RestOperations/TenantsRestOperations.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Threading; -using Azure.Core; - -namespace Azure.ResourceManager.Resources -{ - [CodeGenSuppress("Get", typeof(CancellationToken))] - [CodeGenSuppress("GetAsync", typeof(CancellationToken))] - [CodeGenSuppress("CreateGetRequest")] - internal partial class TenantsRestOperations - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/SubscriptionData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/SubscriptionData.cs deleted file mode 100644 index 01db245a68..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/SubscriptionData.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using Azure.Core; - -namespace Azure.ResourceManager.Resources -{ - /// A class representing the Subscription data model. - public partial class SubscriptionData - { - /// The ARM resource identifier. - public virtual ResourceIdentifier Id { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/SubscriptionResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/SubscriptionResource.cs deleted file mode 100644 index db043c39c0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/SubscriptionResource.cs +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.ComponentModel; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the operations that can be performed over a specific subscription. - /// - public partial class SubscriptionResource : ArmResource - { - /// RequestPath: /subscriptions/{subscriptionId}/resources - /// ContextualPath: /subscriptions/{subscriptionId} - /// OperationId: Resources_List - /// Get all the resources in a subscription. - /// The filter to apply on the operation.<br><br>The properties you can use for eq (equals) or ne (not equals) are: location, resourceType, name, resourceGroup, identity, identity/principalId, plan, plan/publisher, plan/product, plan/name, plan/version, and plan/promotionCode.<br><br>For example, to filter by a resource type, use: $filter=resourceType eq 'Microsoft.Network/virtualNetworks'<br><br>You can use substringof(value, property) in the filter. The properties you can use for substring are: name and resourceGroup.<br><br>For example, to get all resources with 'demo' anywhere in the name, use: $filter=substringof('demo', name)<br><br>You can link more than one substringof together by adding and/or operators.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. When you filter by a tag name and value, the tags for each resource are not returned in the results.<br><br>You can use some properties together when filtering. The combinations you can use are: substringof and/or resourceType, plan and plan/publisher and plan/name, identity and identity/principalId. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of results to return. If null is passed, returns all resource groups. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetGenericResourcesAsync(string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - async Task> FirstPageFunc(int? pageSizeHint) - { - using var scope = _subscriptionClientDiagnostics.CreateScope("SubscriptionResource.GetGenericResources"); - scope.Start(); - try - { - var response = await _subscriptionResourcesRestClient.ListAsync(Id.SubscriptionId, filter, expand, top, cancellationToken: cancellationToken).ConfigureAwait(false); - return Page.FromValues(response.Value.Value.Select(value => new GenericResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - async Task> NextPageFunc(string nextLink, int? pageSizeHint) - { - using var scope = _subscriptionResourcesClientDiagnostics.CreateScope("SubscriptionResource.GetGenericResources"); - scope.Start(); - try - { - var response = await _subscriptionResourcesRestClient.ListNextPageAsync(nextLink, Id.SubscriptionId, filter, expand, top, cancellationToken: cancellationToken).ConfigureAwait(false); - return Page.FromValues(response.Value.Value.Select(value => new GenericResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); - } - - /// RequestPath: /subscriptions/{subscriptionId}/resources - /// ContextualPath: /subscriptions/{subscriptionId} - /// OperationId: Resources_List - /// Get all the resources in a subscription. - /// The filter to apply on the operation.<br><br>The properties you can use for eq (equals) or ne (not equals) are: location, resourceType, name, resourceGroup, identity, identity/principalId, plan, plan/publisher, plan/product, plan/name, plan/version, and plan/promotionCode.<br><br>For example, to filter by a resource type, use: $filter=resourceType eq 'Microsoft.Network/virtualNetworks'<br><br>You can use substringof(value, property) in the filter. The properties you can use for substring are: name and resourceGroup.<br><br>For example, to get all resources with 'demo' anywhere in the name, use: $filter=substringof('demo', name)<br><br>You can link more than one substringof together by adding and/or operators.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. When you filter by a tag name and value, the tags for each resource are not returned in the results.<br><br>You can use some properties together when filtering. The combinations you can use are: substringof and/or resourceType, plan and plan/publisher and plan/name, identity and identity/principalId. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of results to return. If null is passed, returns all resource groups. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetGenericResources(string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Page FirstPageFunc(int? pageSizeHint) - { - using var scope = _subscriptionResourcesClientDiagnostics.CreateScope("SubscriptionResource.GetGenericResources"); - scope.Start(); - try - { - var response = _subscriptionResourcesRestClient.List(Id.SubscriptionId, filter, expand, top, cancellationToken: cancellationToken); - return Page.FromValues(response.Value.Value.Select(value => new GenericResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - Page NextPageFunc(string nextLink, int? pageSizeHint) - { - using var scope = _subscriptionResourcesClientDiagnostics.CreateScope("SubscriptionResource.GetGenericResources"); - scope.Start(); - try - { - var response = _subscriptionResourcesRestClient.ListNextPage(nextLink, Id.SubscriptionId, filter, expand, top, cancellationToken: cancellationToken); - return Page.FromValues(response.Value.Value.Select(value => new GenericResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); - } - - /// - /// Gets the RestApi definition for a given Azure namespace. - /// - /// The namespace to get the rest API for. - /// A collection representing the rest apis for the namespace. - public virtual ArmRestApiCollection GetArmRestApis(string azureNamespace) - { - return new ArmRestApiCollection(this, azureNamespace); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/TagResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/TagResource.cs deleted file mode 100644 index a8e6740e55..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/TagResource.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a TagResource along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetTagResource method. - /// Otherwise you can get one from its parent resource using the GetTagResource method. - /// - public partial class TagResource : ArmResource - { - /// - /// This operation allows replacing, merging or selectively deleting tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags at the end of the operation. The 'replace' option replaces the entire set of existing tags with a new set. The 'merge' option allows adding tags with new names and updating the values of tags with existing names. The 'delete' option allows selectively deleting tags based on given names or name/value pairs. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_UpdateAtScope - /// - /// - /// - /// The TagResourcePatch to use. - /// The cancellation token to use. - /// is null. - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("This method is obsolete and will be removed in a future release.", false)] - public virtual async Task> UpdateAsync(TagResourcePatch patch, CancellationToken cancellationToken = default) - { - var operation = await UpdateAsync(WaitUntil.Completed, patch, cancellationToken).ConfigureAwait(false); - return Response.FromValue(operation.Value, operation.GetRawResponse()); - } - - /// - /// This operation allows replacing, merging or selectively deleting tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags at the end of the operation. The 'replace' option replaces the entire set of existing tags with a new set. The 'merge' option allows adding tags with new names and updating the values of tags with existing names. The 'delete' option allows selectively deleting tags based on given names or name/value pairs. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_UpdateAtScope - /// - /// - /// - /// The TagResourcePatch to use. - /// The cancellation token to use. - /// is null. - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("This method is obsolete and will be removed in a future release.", false)] - public virtual Response Update(TagResourcePatch patch, CancellationToken cancellationToken = default) - { - var operation = Update(WaitUntil.Completed, patch, cancellationToken); - return Response.FromValue(operation.Value, operation.GetRawResponse()); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/TenantCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/TenantCollection.cs deleted file mode 100644 index 9a4f57e413..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/TenantCollection.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.Collections.Generic; -using System.Threading; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing collection of TenantResource and their operations over their parent. - /// - [CodeGenSuppress("Get", typeof(CancellationToken))] - [CodeGenSuppress("GetAsync", typeof(CancellationToken))] - [CodeGenSuppress("Exists", typeof(CancellationToken))] - [CodeGenSuppress("ExistsAsync", typeof(CancellationToken))] - [CodeGenSuppress("GetIfExists", typeof(CancellationToken))] - [CodeGenSuppress("GetIfExistsAsync", typeof(CancellationToken))] - public partial class TenantCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - /// Initializes a new instance of the class. - /// The resource representing the parent resource. - internal TenantCollection(ArmClient client) : this(client, ResourceIdentifier.Root) - { - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/TenantResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/TenantResource.cs deleted file mode 100644 index 6fadc0c833..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Custom/TenantResource.cs +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -[assembly: CodeGenSuppressType("TenantExtensions")] -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the operations that can be performed over a specific subscription. - /// - [CodeGenSuppress("TenantResource", typeof(ArmClient), typeof(TenantData))] - [CodeGenSuppress("Get", typeof(CancellationToken))] - [CodeGenSuppress("GetAsync", typeof(CancellationToken))] - [CodeGenSuppress("GetAvailableLocations", typeof(CancellationToken))] - [CodeGenSuppress("GetAvailableLocationsAsync", typeof(CancellationToken))] - [CodeGenSuppress("GetTenants")] - [CodeGenSuppress("CreateResourceIdentifier")] - [CodeGenSuppress("GetGenericResourceAsync", typeof(ResourceIdentifier), typeof(string), typeof(CancellationToken))] - [CodeGenSuppress("GetGenericResource", typeof(ResourceIdentifier), typeof(string), typeof(CancellationToken))] - // [CodeGenSuppress("_tenantsRestClient")] // TODO: not working for private member - public partial class TenantResource : ArmResource - { - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - internal TenantResource(ArmClient client) : this(client, ResourceIdentifier.Root) - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal TenantResource(ArmClient client, TenantData data) : this(client, ResourceIdentifier.Root) - { - HasData = true; - _data = data; - } - - /// - /// Gets all resource providers for the tenant. - /// - /// - /// Request Path - /// /providers - /// - /// - /// Operation Id - /// Providers_ListAtTenantScope - /// - /// - /// - /// [This parameter is no longer supported.] The number of results to return. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("This method is obsolete as the `top` parameter is not supported by service and will be removed in a future release.", false)] - public virtual AsyncPageable GetTenantResourceProvidersAsync(int? top, string expand, CancellationToken cancellationToken = default) - { - return GetTenantResourceProvidersAsync(expand, cancellationToken); - } - - /// - /// Gets all resource providers for the tenant. - /// - /// - /// Request Path - /// /providers - /// - /// - /// Operation Id - /// Providers_ListAtTenantScope - /// - /// - /// - /// [This parameter is no longer supported.] The number of results to return. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("This method is obsolete as the `top` parameter is not supported by service and will be removed in a future release.", false)] - public virtual Pageable GetTenantResourceProviders(int? top, string expand, CancellationToken cancellationToken = default) - { - return GetTenantResourceProviders(expand, cancellationToken); - } - - /// - /// Gets a resource by ID. - /// - /// - /// Request Path - /// /{resourceId} - /// - /// - /// Operation Id - /// Resources_GetById - /// - /// - /// - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The cancellation token to use. - /// is null. - // api-version is defined as method parameter in spec but used as client parameter for Resources_GetById to keep the contract unchaged - [ForwardsClientCalls] - public virtual async Task> GetGenericResourceAsync(ResourceIdentifier resourceId, CancellationToken cancellationToken = default) - { - return await GetGenericResources().GetAsync(resourceId, cancellationToken).ConfigureAwait(false); - } - - /// - /// Gets a resource by ID. - /// - /// - /// Request Path - /// /{resourceId} - /// - /// - /// Operation Id - /// Resources_GetById - /// - /// - /// - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The cancellation token to use. - /// is null. - // api-version is defined as method parameter in spec but used as client parameter for Resources_GetById to keep the contract unchaged - [ForwardsClientCalls] - public virtual Response GetGenericResource(ResourceIdentifier resourceId, CancellationToken cancellationToken = default) - { - return GetGenericResources().Get(resourceId, cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestCollection.cs deleted file mode 100644 index 3d94174f1d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestCollection.cs +++ /dev/null @@ -1,396 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetDataPolicyManifests method from an instance of . - /// - public partial class DataPolicyManifestCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _dataPolicyManifestClientDiagnostics; - private readonly DataPolicyManifestsRestOperations _dataPolicyManifestRestClient; - - /// Initializes a new instance of the class for mocking. - protected DataPolicyManifestCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal DataPolicyManifestCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _dataPolicyManifestClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", DataPolicyManifestResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(DataPolicyManifestResource.ResourceType, out string dataPolicyManifestApiVersion); - _dataPolicyManifestRestClient = new DataPolicyManifestsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, dataPolicyManifestApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != TenantResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, TenantResource.ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the data policy manifest with the given policy mode. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string policyMode, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyMode, nameof(policyMode)); - - using var scope = _dataPolicyManifestClientDiagnostics.CreateScope("DataPolicyManifestCollection.Get"); - scope.Start(); - try - { - var response = await _dataPolicyManifestRestClient.GetByPolicyModeAsync(policyMode, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new DataPolicyManifestResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the data policy manifest with the given policy mode. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string policyMode, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyMode, nameof(policyMode)); - - using var scope = _dataPolicyManifestClientDiagnostics.CreateScope("DataPolicyManifestCollection.Get"); - scope.Start(); - try - { - var response = _dataPolicyManifestRestClient.GetByPolicyMode(policyMode, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new DataPolicyManifestResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a list of all the data policy manifests that match the optional given $filter. Valid values for $filter are: "$filter=namespace eq '{0}'". If $filter is not provided, the unfiltered list includes all data policy manifests for data resource types. If $filter=namespace is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests - /// - /// - /// Operation Id - /// DataPolicyManifests_List - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: "namespace eq '{value}'". If $filter is not provided, no filtering is performed. If $filter=namespace eq '{value}' is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _dataPolicyManifestRestClient.CreateListRequest(filter); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _dataPolicyManifestRestClient.CreateListNextPageRequest(nextLink, filter); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new DataPolicyManifestResource(Client, DataPolicyManifestData.DeserializeDataPolicyManifestData(e)), _dataPolicyManifestClientDiagnostics, Pipeline, "DataPolicyManifestCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// This operation retrieves a list of all the data policy manifests that match the optional given $filter. Valid values for $filter are: "$filter=namespace eq '{0}'". If $filter is not provided, the unfiltered list includes all data policy manifests for data resource types. If $filter=namespace is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests - /// - /// - /// Operation Id - /// DataPolicyManifests_List - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: "namespace eq '{value}'". If $filter is not provided, no filtering is performed. If $filter=namespace eq '{value}' is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _dataPolicyManifestRestClient.CreateListRequest(filter); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _dataPolicyManifestRestClient.CreateListNextPageRequest(nextLink, filter); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new DataPolicyManifestResource(Client, DataPolicyManifestData.DeserializeDataPolicyManifestData(e)), _dataPolicyManifestClientDiagnostics, Pipeline, "DataPolicyManifestCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string policyMode, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyMode, nameof(policyMode)); - - using var scope = _dataPolicyManifestClientDiagnostics.CreateScope("DataPolicyManifestCollection.Exists"); - scope.Start(); - try - { - var response = await _dataPolicyManifestRestClient.GetByPolicyModeAsync(policyMode, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string policyMode, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyMode, nameof(policyMode)); - - using var scope = _dataPolicyManifestClientDiagnostics.CreateScope("DataPolicyManifestCollection.Exists"); - scope.Start(); - try - { - var response = _dataPolicyManifestRestClient.GetByPolicyMode(policyMode, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string policyMode, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyMode, nameof(policyMode)); - - using var scope = _dataPolicyManifestClientDiagnostics.CreateScope("DataPolicyManifestCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _dataPolicyManifestRestClient.GetByPolicyModeAsync(policyMode, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new DataPolicyManifestResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string policyMode, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyMode, nameof(policyMode)); - - using var scope = _dataPolicyManifestClientDiagnostics.CreateScope("DataPolicyManifestCollection.GetIfExists"); - scope.Start(); - try - { - var response = _dataPolicyManifestRestClient.GetByPolicyMode(policyMode, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new DataPolicyManifestResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestData.Serialization.cs deleted file mode 100644 index ffdbb48171..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestData.Serialization.cs +++ /dev/null @@ -1,647 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class DataPolicyManifestData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataPolicyManifestData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (Optional.IsCollectionDefined(Namespaces)) - { - writer.WritePropertyName("namespaces"u8); - writer.WriteStartArray(); - foreach (var item in Namespaces) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(PolicyMode)) - { - writer.WritePropertyName("policyMode"u8); - writer.WriteStringValue(PolicyMode); - } - if (Optional.IsDefined(IsBuiltInOnly)) - { - writer.WritePropertyName("isBuiltInOnly"u8); - writer.WriteBooleanValue(IsBuiltInOnly.Value); - } - if (Optional.IsCollectionDefined(ResourceTypeAliases)) - { - writer.WritePropertyName("resourceTypeAliases"u8); - writer.WriteStartArray(); - foreach (var item in ResourceTypeAliases) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(Effects)) - { - writer.WritePropertyName("effects"u8); - writer.WriteStartArray(); - foreach (var item in Effects) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(FieldValues)) - { - writer.WritePropertyName("fieldValues"u8); - writer.WriteStartArray(); - foreach (var item in FieldValues) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - writer.WritePropertyName("resourceFunctions"u8); - writer.WriteStartObject(); - if (Optional.IsCollectionDefined(Standard)) - { - writer.WritePropertyName("standard"u8); - writer.WriteStartArray(); - foreach (var item in Standard) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(CustomDefinitions)) - { - writer.WritePropertyName("custom"u8); - writer.WriteStartArray(); - foreach (var item in CustomDefinitions) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - writer.WriteEndObject(); - writer.WriteEndObject(); - } - - DataPolicyManifestData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataPolicyManifestData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDataPolicyManifestData(document.RootElement, options); - } - - internal static DataPolicyManifestData DeserializeDataPolicyManifestData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - IReadOnlyList namespaces = default; - string policyMode = default; - bool? isBuiltInOnly = default; - IReadOnlyList resourceTypeAliases = default; - IReadOnlyList effects = default; - IReadOnlyList fieldValues = default; - IReadOnlyList standard = default; - IReadOnlyList custom = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("namespaces"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - namespaces = array; - continue; - } - if (property0.NameEquals("policyMode"u8)) - { - policyMode = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("isBuiltInOnly"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - isBuiltInOnly = property0.Value.GetBoolean(); - continue; - } - if (property0.NameEquals("resourceTypeAliases"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(Models.ResourceTypeAliases.DeserializeResourceTypeAliases(item, options)); - } - resourceTypeAliases = array; - continue; - } - if (property0.NameEquals("effects"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(DataPolicyManifestEffect.DeserializeDataPolicyManifestEffect(item, options)); - } - effects = array; - continue; - } - if (property0.NameEquals("fieldValues"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - fieldValues = array; - continue; - } - if (property0.NameEquals("resourceFunctions"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - property0.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property1 in property0.Value.EnumerateObject()) - { - if (property1.NameEquals("standard"u8)) - { - if (property1.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property1.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - standard = array; - continue; - } - if (property1.NameEquals("custom"u8)) - { - if (property1.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property1.Value.EnumerateArray()) - { - array.Add(DataManifestCustomResourceFunctionDefinition.DeserializeDataManifestCustomResourceFunctionDefinition(item, options)); - } - custom = array; - continue; - } - } - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new DataPolicyManifestData( - id, - name, - type, - systemData, - namespaces ?? new ChangeTrackingList(), - policyMode, - isBuiltInOnly, - resourceTypeAliases ?? new ChangeTrackingList(), - effects ?? new ChangeTrackingList(), - fieldValues ?? new ChangeTrackingList(), - standard ?? new ChangeTrackingList(), - custom ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.Append(" properties:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Namespaces), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" namespaces: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Namespaces)) - { - if (Namespaces.Any()) - { - builder.Append(" namespaces: "); - builder.AppendLine("["); - foreach (var item in Namespaces) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyMode), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyMode: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PolicyMode)) - { - builder.Append(" policyMode: "); - if (PolicyMode.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{PolicyMode}'''"); - } - else - { - builder.AppendLine($"'{PolicyMode}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(IsBuiltInOnly), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" isBuiltInOnly: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(IsBuiltInOnly)) - { - builder.Append(" isBuiltInOnly: "); - var boolValue = IsBuiltInOnly.Value == true ? "true" : "false"; - builder.AppendLine($"{boolValue}"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ResourceTypeAliases), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" resourceTypeAliases: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ResourceTypeAliases)) - { - if (ResourceTypeAliases.Any()) - { - builder.Append(" resourceTypeAliases: "); - builder.AppendLine("["); - foreach (var item in ResourceTypeAliases) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 6, true, " resourceTypeAliases: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Effects), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" effects: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Effects)) - { - if (Effects.Any()) - { - builder.Append(" effects: "); - builder.AppendLine("["); - foreach (var item in Effects) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 6, true, " effects: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(FieldValues), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" fieldValues: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(FieldValues)) - { - if (FieldValues.Any()) - { - builder.Append(" fieldValues: "); - builder.AppendLine("["); - foreach (var item in FieldValues) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - builder.Append(" resourceFunctions:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Standard), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" standard: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Standard)) - { - if (Standard.Any()) - { - builder.Append(" standard: "); - builder.AppendLine("["); - foreach (var item in Standard) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(CustomDefinitions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" custom: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(CustomDefinitions)) - { - if (CustomDefinitions.Any()) - { - builder.Append(" custom: "); - builder.AppendLine("["); - foreach (var item in CustomDefinitions) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 8, true, " custom: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine(" }"); - builder.AppendLine(" }"); - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(DataPolicyManifestData)} does not support writing '{options.Format}' format."); - } - } - - DataPolicyManifestData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeDataPolicyManifestData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DataPolicyManifestData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestData.cs deleted file mode 100644 index 32ace96c4d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestData.cs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the DataPolicyManifest data model. - /// The data policy manifest. - /// - public partial class DataPolicyManifestData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal DataPolicyManifestData() - { - Namespaces = new ChangeTrackingList(); - ResourceTypeAliases = new ChangeTrackingList(); - Effects = new ChangeTrackingList(); - FieldValues = new ChangeTrackingList(); - Standard = new ChangeTrackingList(); - CustomDefinitions = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The list of namespaces for the data policy manifest. - /// The policy mode of the data policy manifest. - /// A value indicating whether policy mode is allowed only in built-in definitions. - /// An array of resource type aliases. - /// The effect definition. - /// The non-alias field accessor values that can be used in the policy rule. - /// The standard resource functions (subscription and/or resourceGroup). - /// An array of data manifest custom resource definition. - /// Keeps track of any properties unknown to the library. - internal DataPolicyManifestData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, IReadOnlyList namespaces, string policyMode, bool? isBuiltInOnly, IReadOnlyList resourceTypeAliases, IReadOnlyList effects, IReadOnlyList fieldValues, IReadOnlyList standard, IReadOnlyList customDefinitions, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - Namespaces = namespaces; - PolicyMode = policyMode; - IsBuiltInOnly = isBuiltInOnly; - ResourceTypeAliases = resourceTypeAliases; - Effects = effects; - FieldValues = fieldValues; - Standard = standard; - CustomDefinitions = customDefinitions; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The list of namespaces for the data policy manifest. - [WirePath("properties.namespaces")] - public IReadOnlyList Namespaces { get; } - /// The policy mode of the data policy manifest. - [WirePath("properties.policyMode")] - public string PolicyMode { get; } - /// A value indicating whether policy mode is allowed only in built-in definitions. - [WirePath("properties.isBuiltInOnly")] - public bool? IsBuiltInOnly { get; } - /// An array of resource type aliases. - [WirePath("properties.resourceTypeAliases")] - public IReadOnlyList ResourceTypeAliases { get; } - /// The effect definition. - [WirePath("properties.effects")] - public IReadOnlyList Effects { get; } - /// The non-alias field accessor values that can be used in the policy rule. - [WirePath("properties.fieldValues")] - public IReadOnlyList FieldValues { get; } - /// The standard resource functions (subscription and/or resourceGroup). - [WirePath("properties.standard")] - public IReadOnlyList Standard { get; } - /// An array of data manifest custom resource definition. - [WirePath("properties.custom")] - public IReadOnlyList CustomDefinitions { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestResource.Serialization.cs deleted file mode 100644 index 6c713c5dfe..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class DataPolicyManifestResource : IJsonModel - { - private static DataPolicyManifestData s_dataDeserializationInstance; - private static DataPolicyManifestData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - DataPolicyManifestData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - DataPolicyManifestData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestResource.cs deleted file mode 100644 index 62e06308fa..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestResource.cs +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a DataPolicyManifest along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetDataPolicyManifestResource method. - /// Otherwise you can get one from its parent resource using the GetDataPolicyManifest method. - /// - public partial class DataPolicyManifestResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The policyMode. - public static ResourceIdentifier CreateResourceIdentifier(string policyMode) - { - var resourceId = $"/providers/Microsoft.Authorization/dataPolicyManifests/{policyMode}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _dataPolicyManifestClientDiagnostics; - private readonly DataPolicyManifestsRestOperations _dataPolicyManifestRestClient; - private readonly DataPolicyManifestData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Authorization/dataPolicyManifests"; - - /// Initializes a new instance of the class for mocking. - protected DataPolicyManifestResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal DataPolicyManifestResource(ArmClient client, DataPolicyManifestData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal DataPolicyManifestResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _dataPolicyManifestClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string dataPolicyManifestApiVersion); - _dataPolicyManifestRestClient = new DataPolicyManifestsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, dataPolicyManifestApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual DataPolicyManifestData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the data policy manifest with the given policy mode. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _dataPolicyManifestClientDiagnostics.CreateScope("DataPolicyManifestResource.Get"); - scope.Start(); - try - { - var response = await _dataPolicyManifestRestClient.GetByPolicyModeAsync(Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new DataPolicyManifestResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the data policy manifest with the given policy mode. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _dataPolicyManifestClientDiagnostics.CreateScope("DataPolicyManifestResource.Get"); - scope.Start(); - try - { - var response = _dataPolicyManifestRestClient.GetByPolicyMode(Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new DataPolicyManifestResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Extensions/ArmClient.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Extensions/ArmClient.cs deleted file mode 100644 index 611e8d348a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Extensions/ArmClient.cs +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using Azure.Core; -using Azure.ResourceManager.Resources; - -namespace Azure.ResourceManager -{ - public partial class ArmClient - { - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual PolicyAssignmentResource GetPolicyAssignmentResource(ResourceIdentifier id) - { - PolicyAssignmentResource.ValidateResourceId(id); - return new PolicyAssignmentResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual SubscriptionPolicyDefinitionResource GetSubscriptionPolicyDefinitionResource(ResourceIdentifier id) - { - SubscriptionPolicyDefinitionResource.ValidateResourceId(id); - return new SubscriptionPolicyDefinitionResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual TenantPolicyDefinitionResource GetTenantPolicyDefinitionResource(ResourceIdentifier id) - { - TenantPolicyDefinitionResource.ValidateResourceId(id); - return new TenantPolicyDefinitionResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual ManagementGroupPolicyDefinitionResource GetManagementGroupPolicyDefinitionResource(ResourceIdentifier id) - { - ManagementGroupPolicyDefinitionResource.ValidateResourceId(id); - return new ManagementGroupPolicyDefinitionResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual SubscriptionPolicySetDefinitionResource GetSubscriptionPolicySetDefinitionResource(ResourceIdentifier id) - { - SubscriptionPolicySetDefinitionResource.ValidateResourceId(id); - return new SubscriptionPolicySetDefinitionResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual TenantPolicySetDefinitionResource GetTenantPolicySetDefinitionResource(ResourceIdentifier id) - { - TenantPolicySetDefinitionResource.ValidateResourceId(id); - return new TenantPolicySetDefinitionResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual ManagementGroupPolicySetDefinitionResource GetManagementGroupPolicySetDefinitionResource(ResourceIdentifier id) - { - ManagementGroupPolicySetDefinitionResource.ValidateResourceId(id); - return new ManagementGroupPolicySetDefinitionResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual DataPolicyManifestResource GetDataPolicyManifestResource(ResourceIdentifier id) - { - DataPolicyManifestResource.ValidateResourceId(id); - return new DataPolicyManifestResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual ManagementLockResource GetManagementLockResource(ResourceIdentifier id) - { - ManagementLockResource.ValidateResourceId(id); - return new ManagementLockResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual ResourceProviderResource GetResourceProviderResource(ResourceIdentifier id) - { - ResourceProviderResource.ValidateResourceId(id); - return new ResourceProviderResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual ResourceGroupResource GetResourceGroupResource(ResourceIdentifier id) - { - ResourceGroupResource.ValidateResourceId(id); - return new ResourceGroupResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual TagResource GetTagResource(ResourceIdentifier id) - { - TagResource.ValidateResourceId(id); - return new TagResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual SubscriptionResource GetSubscriptionResource(ResourceIdentifier id) - { - SubscriptionResource.ValidateResourceId(id); - return new SubscriptionResource(this, id); - } - - /// - /// Gets an object representing a along with the instance operations that can be performed on it but with no data. - /// You can use to create a from its components. - /// - /// The resource ID of the resource to get. - /// Returns a object. - public virtual FeatureResource GetFeatureResource(ResourceIdentifier id) - { - FeatureResource.ValidateResourceId(id); - return new FeatureResource(this, id); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Extensions/ArmResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Extensions/ArmResource.cs deleted file mode 100644 index a70590323b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Extensions/ArmResource.cs +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.ResourceManager.Resources; - -namespace Azure.ResourceManager -{ - public partial class ArmResource - { - /// Gets a collection of PolicyAssignmentResources in the ArmResource. - /// An object representing collection of PolicyAssignmentResources and their operations over a PolicyAssignmentResource. - public virtual PolicyAssignmentCollection GetPolicyAssignments() - { - return GetCachedClient(client => new PolicyAssignmentCollection(client, Id)); - } - - /// - /// This operation retrieves a single policy assignment, given its name and the scope it was created at. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetPolicyAssignmentAsync(string policyAssignmentName, CancellationToken cancellationToken = default) - { - return await GetPolicyAssignments().GetAsync(policyAssignmentName, cancellationToken).ConfigureAwait(false); - } - - /// - /// This operation retrieves a single policy assignment, given its name and the scope it was created at. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetPolicyAssignment(string policyAssignmentName, CancellationToken cancellationToken = default) - { - return GetPolicyAssignments().Get(policyAssignmentName, cancellationToken); - } - - /// Gets a collection of ManagementLockResources in the ArmResource. - /// An object representing collection of ManagementLockResources and their operations over a ManagementLockResource. - public virtual ManagementLockCollection GetManagementLocks() - { - return GetCachedClient(client => new ManagementLockCollection(client, Id)); - } - - /// - /// Get a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of lock. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetManagementLockAsync(string lockName, CancellationToken cancellationToken = default) - { - return await GetManagementLocks().GetAsync(lockName, cancellationToken).ConfigureAwait(false); - } - - /// - /// Get a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of lock. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetManagementLock(string lockName, CancellationToken cancellationToken = default) - { - return GetManagementLocks().Get(lockName, cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Extensions/ManagementGroupResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Extensions/ManagementGroupResource.cs deleted file mode 100644 index 2e6a3a5047..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Extensions/ManagementGroupResource.cs +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.ResourceManager.Resources; - -namespace Azure.ResourceManager.ManagementGroups -{ - public partial class ManagementGroupResource - { - /// Gets a collection of ManagementGroupPolicyDefinitionResources in the ManagementGroupResource. - /// An object representing collection of ManagementGroupPolicyDefinitionResources and their operations over a ManagementGroupPolicyDefinitionResource. - public virtual ManagementGroupPolicyDefinitionCollection GetManagementGroupPolicyDefinitions() - { - return GetCachedClient(client => new ManagementGroupPolicyDefinitionCollection(client, Id)); - } - - /// - /// This operation retrieves the policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetManagementGroupPolicyDefinitionAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - return await GetManagementGroupPolicyDefinitions().GetAsync(policyDefinitionName, cancellationToken).ConfigureAwait(false); - } - - /// - /// This operation retrieves the policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetManagementGroupPolicyDefinition(string policyDefinitionName, CancellationToken cancellationToken = default) - { - return GetManagementGroupPolicyDefinitions().Get(policyDefinitionName, cancellationToken); - } - - /// Gets a collection of ManagementGroupPolicySetDefinitionResources in the ManagementGroupResource. - /// An object representing collection of ManagementGroupPolicySetDefinitionResources and their operations over a ManagementGroupPolicySetDefinitionResource. - public virtual ManagementGroupPolicySetDefinitionCollection GetManagementGroupPolicySetDefinitions() - { - return GetCachedClient(client => new ManagementGroupPolicySetDefinitionCollection(client, Id)); - } - - /// - /// This operation retrieves the policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetManagementGroupPolicySetDefinitionAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - return await GetManagementGroupPolicySetDefinitions().GetAsync(policySetDefinitionName, cancellationToken).ConfigureAwait(false); - } - - /// - /// This operation retrieves the policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetManagementGroupPolicySetDefinition(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - return GetManagementGroupPolicySetDefinitions().Get(policySetDefinitionName, cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureCollection.cs deleted file mode 100644 index a0c55991a2..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureCollection.cs +++ /dev/null @@ -1,394 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetFeatures method from an instance of . - /// - public partial class FeatureCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _featureClientDiagnostics; - private readonly FeaturesRestOperations _featureRestClient; - - /// Initializes a new instance of the class for mocking. - protected FeatureCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal FeatureCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _featureClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", FeatureResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(FeatureResource.ResourceType, out string featureApiVersion); - _featureRestClient = new FeaturesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, featureApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceProviderResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceProviderResource.ResourceType), nameof(id)); - } - - /// - /// Gets the preview feature with the specified name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the feature to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var scope = _featureClientDiagnostics.CreateScope("FeatureCollection.Get"); - scope.Start(); - try - { - var response = await _featureRestClient.GetAsync(Id.SubscriptionId, Id.Provider, featureName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets the preview feature with the specified name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the feature to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var scope = _featureClientDiagnostics.CreateScope("FeatureCollection.Get"); - scope.Start(); - try - { - var response = _featureRestClient.Get(Id.SubscriptionId, Id.Provider, featureName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets all the preview features in a provider namespace that are available through AFEC for the subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features - /// - /// - /// Operation Id - /// Features_List - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _featureRestClient.CreateListRequest(Id.SubscriptionId, Id.Provider); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _featureRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, Id.Provider); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new FeatureResource(Client, FeatureData.DeserializeFeatureData(e)), _featureClientDiagnostics, Pipeline, "FeatureCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Gets all the preview features in a provider namespace that are available through AFEC for the subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features - /// - /// - /// Operation Id - /// Features_List - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _featureRestClient.CreateListRequest(Id.SubscriptionId, Id.Provider); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _featureRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, Id.Provider); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new FeatureResource(Client, FeatureData.DeserializeFeatureData(e)), _featureClientDiagnostics, Pipeline, "FeatureCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the feature to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var scope = _featureClientDiagnostics.CreateScope("FeatureCollection.Exists"); - scope.Start(); - try - { - var response = await _featureRestClient.GetAsync(Id.SubscriptionId, Id.Provider, featureName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the feature to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var scope = _featureClientDiagnostics.CreateScope("FeatureCollection.Exists"); - scope.Start(); - try - { - var response = _featureRestClient.Get(Id.SubscriptionId, Id.Provider, featureName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the feature to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var scope = _featureClientDiagnostics.CreateScope("FeatureCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _featureRestClient.GetAsync(Id.SubscriptionId, Id.Provider, featureName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the feature to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var scope = _featureClientDiagnostics.CreateScope("FeatureCollection.GetIfExists"); - scope.Start(); - try - { - var response = _featureRestClient.Get(Id.SubscriptionId, Id.Provider, featureName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureData.Serialization.cs deleted file mode 100644 index 5613878760..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureData.Serialization.cs +++ /dev/null @@ -1,244 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class FeatureData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(FeatureData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - if (Optional.IsDefined(Properties)) - { - writer.WritePropertyName("properties"u8); - writer.WriteObjectValue(Properties, options); - } - } - - FeatureData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(FeatureData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeFeatureData(document.RootElement, options); - } - - internal static FeatureData DeserializeFeatureData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - FeatureProperties properties = default; - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - properties = FeatureProperties.DeserializeFeatureProperties(property.Value, options); - continue; - } - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new FeatureData( - id, - name, - type, - systemData, - properties, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue("FeatureState", out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" properties: "); - builder.AppendLine("{"); - builder.Append(" state: "); - builder.AppendLine(propertyOverride); - builder.AppendLine(" }"); - } - else - { - if (Optional.IsDefined(Properties)) - { - builder.Append(" properties: "); - BicepSerializationHelpers.AppendChildObject(builder, Properties, options, 2, false, " properties: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(FeatureData)} does not support writing '{options.Format}' format."); - } - } - - FeatureData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeFeatureData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(FeatureData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureData.cs deleted file mode 100644 index ef7d2ec42c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureData.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the Feature data model. - /// Previewed feature information. - /// - public partial class FeatureData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal FeatureData() - { - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// Properties of the previewed feature. - /// Keeps track of any properties unknown to the library. - internal FeatureData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, FeatureProperties properties, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - Properties = properties; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Properties of the previewed feature. - internal FeatureProperties Properties { get; } - /// The registration state of the feature for the subscription. - [WirePath("properties.state")] - public string FeatureState - { - get => Properties?.State; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureResource.Serialization.cs deleted file mode 100644 index 264d1675fc..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class FeatureResource : IJsonModel - { - private static FeatureData s_dataDeserializationInstance; - private static FeatureData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - FeatureData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - FeatureData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureResource.cs deleted file mode 100644 index 463ada11d3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/FeatureResource.cs +++ /dev/null @@ -1,316 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a Feature along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetFeatureResource method. - /// Otherwise you can get one from its parent resource using the GetFeature method. - /// - public partial class FeatureResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The subscriptionId. - /// The resourceProviderNamespace. - /// The featureName. - public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceProviderNamespace, string featureName) - { - var resourceId = $"/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _featureClientDiagnostics; - private readonly FeaturesRestOperations _featureRestClient; - private readonly FeatureData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Resources/features"; - - /// Initializes a new instance of the class for mocking. - protected FeatureResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal FeatureResource(ArmClient client, FeatureData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal FeatureResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _featureClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string featureApiVersion); - _featureRestClient = new FeaturesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, featureApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual FeatureData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - /// - /// Gets the preview feature with the specified name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _featureClientDiagnostics.CreateScope("FeatureResource.Get"); - scope.Start(); - try - { - var response = await _featureRestClient.GetAsync(Id.SubscriptionId, Id.ResourceType.Namespace, Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets the preview feature with the specified name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _featureClientDiagnostics.CreateScope("FeatureResource.Get"); - scope.Start(); - try - { - var response = _featureRestClient.Get(Id.SubscriptionId, Id.ResourceType.Namespace, Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Registers the preview feature for the subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/register - /// - /// - /// Operation Id - /// Features_Register - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> RegisterAsync(CancellationToken cancellationToken = default) - { - using var scope = _featureClientDiagnostics.CreateScope("FeatureResource.Register"); - scope.Start(); - try - { - var response = await _featureRestClient.RegisterAsync(Id.SubscriptionId, Id.ResourceType.Namespace, Id.Name, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Registers the preview feature for the subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/register - /// - /// - /// Operation Id - /// Features_Register - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Register(CancellationToken cancellationToken = default) - { - using var scope = _featureClientDiagnostics.CreateScope("FeatureResource.Register"); - scope.Start(); - try - { - var response = _featureRestClient.Register(Id.SubscriptionId, Id.ResourceType.Namespace, Id.Name, cancellationToken); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Unregisters the preview feature for the subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/unregister - /// - /// - /// Operation Id - /// Features_Unregister - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> UnregisterAsync(CancellationToken cancellationToken = default) - { - using var scope = _featureClientDiagnostics.CreateScope("FeatureResource.Unregister"); - scope.Start(); - try - { - var response = await _featureRestClient.UnregisterAsync(Id.SubscriptionId, Id.ResourceType.Namespace, Id.Name, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Unregisters the preview feature for the subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/unregister - /// - /// - /// Operation Id - /// Features_Unregister - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Unregister(CancellationToken cancellationToken = default) - { - using var scope = _featureClientDiagnostics.CreateScope("FeatureResource.Unregister"); - scope.Start(); - try - { - var response = _featureRestClient.Unregister(Id.SubscriptionId, Id.ResourceType.Namespace, Id.Name, cancellationToken); - return Response.FromValue(new FeatureResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/GenericResourceData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/GenericResourceData.Serialization.cs deleted file mode 100644 index 1f3364c8b0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/GenericResourceData.Serialization.cs +++ /dev/null @@ -1,609 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class GenericResourceData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(GenericResourceData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - if (Optional.IsDefined(Plan)) - { - writer.WritePropertyName("plan"u8); - JsonSerializer.Serialize(writer, Plan); - } - if (Optional.IsDefined(Properties)) - { - writer.WritePropertyName("properties"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(Properties); -#else - using (JsonDocument document = JsonDocument.Parse(Properties, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - if (Optional.IsDefined(Kind)) - { - writer.WritePropertyName("kind"u8); - writer.WriteStringValue(Kind); - } - if (Optional.IsDefined(ManagedBy)) - { - writer.WritePropertyName("managedBy"u8); - writer.WriteStringValue(ManagedBy); - } - if (Optional.IsDefined(Sku)) - { - writer.WritePropertyName("sku"u8); - writer.WriteObjectValue(Sku, options); - } - if (Optional.IsDefined(Identity)) - { - writer.WritePropertyName("identity"u8); - JsonSerializer.Serialize(writer, Identity); - } - if (options.Format != "W" && Optional.IsDefined(CreatedOn)) - { - writer.WritePropertyName("createdTime"u8); - writer.WriteStringValue(CreatedOn.Value, "O"); - } - if (options.Format != "W" && Optional.IsDefined(ChangedOn)) - { - writer.WritePropertyName("changedTime"u8); - writer.WriteStringValue(ChangedOn.Value, "O"); - } - if (options.Format != "W" && Optional.IsDefined(ProvisioningState)) - { - writer.WritePropertyName("provisioningState"u8); - writer.WriteStringValue(ProvisioningState); - } - } - - GenericResourceData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(GenericResourceData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeGenericResourceData(document.RootElement, options); - } - - internal static GenericResourceData DeserializeGenericResourceData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ArmPlan plan = default; - BinaryData properties = default; - string kind = default; - string managedBy = default; - ResourcesSku sku = default; - ManagedServiceIdentity identity = default; - DateTimeOffset? createdTime = default; - DateTimeOffset? changedTime = default; - string provisioningState = default; - ExtendedLocation extendedLocation = default; - IDictionary tags = default; - AzureLocation location = default; - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("plan"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - plan = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - properties = BinaryData.FromString(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("kind"u8)) - { - kind = property.Value.GetString(); - continue; - } - if (property.NameEquals("managedBy"u8)) - { - managedBy = property.Value.GetString(); - continue; - } - if (property.NameEquals("sku"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - sku = ResourcesSku.DeserializeResourcesSku(property.Value, options); - continue; - } - if (property.NameEquals("identity"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - identity = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("createdTime"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - createdTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("changedTime"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - changedTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("provisioningState"u8)) - { - provisioningState = property.Value.GetString(); - continue; - } - if (property.NameEquals("extendedLocation"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - extendedLocation = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("tags"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - tags = dictionary; - continue; - } - if (property.NameEquals("location"u8)) - { - location = new AzureLocation(property.Value.GetString()); - continue; - } - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new GenericResourceData( - id, - name, - type, - systemData, - tags ?? new ChangeTrackingDictionary(), - location, - extendedLocation, - serializedAdditionalRawData, - plan, - properties, - kind, - managedBy, - sku, - identity, - createdTime, - changedTime, - provisioningState); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Location), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" location: "); - builder.AppendLine(propertyOverride); - } - else - { - builder.Append(" location: "); - builder.AppendLine($"'{Location.ToString()}'"); - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Tags), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tags: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Tags)) - { - if (Tags.Any()) - { - builder.Append(" tags: "); - builder.AppendLine("{"); - foreach (var item in Tags) - { - builder.Append($" '{item.Key}': "); - if (item.Value == null) - { - builder.Append("null"); - continue; - } - if (item.Value.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{item.Value}'''"); - } - else - { - builder.AppendLine($"'{item.Value}'"); - } - } - builder.AppendLine(" }"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Plan), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" plan: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Plan)) - { - builder.Append(" plan: "); - BicepSerializationHelpers.AppendChildObject(builder, Plan, options, 2, false, " plan: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Properties), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" properties: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Properties)) - { - builder.Append(" properties: "); - builder.AppendLine($"'{Properties.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Kind), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" kind: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Kind)) - { - builder.Append(" kind: "); - if (Kind.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Kind}'''"); - } - else - { - builder.AppendLine($"'{Kind}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ManagedBy), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" managedBy: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ManagedBy)) - { - builder.Append(" managedBy: "); - if (ManagedBy.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ManagedBy}'''"); - } - else - { - builder.AppendLine($"'{ManagedBy}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Sku), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" sku: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Sku)) - { - builder.Append(" sku: "); - BicepSerializationHelpers.AppendChildObject(builder, Sku, options, 2, false, " sku: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Identity), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" identity: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Identity)) - { - builder.Append(" identity: "); - BicepSerializationHelpers.AppendChildObject(builder, Identity, options, 2, false, " identity: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(CreatedOn), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" createdTime: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(CreatedOn)) - { - builder.Append(" createdTime: "); - var formattedDateTimeString = TypeFormatters.ToString(CreatedOn.Value, "o"); - builder.AppendLine($"'{formattedDateTimeString}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ChangedOn), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" changedTime: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ChangedOn)) - { - builder.Append(" changedTime: "); - var formattedDateTimeString = TypeFormatters.ToString(ChangedOn.Value, "o"); - builder.AppendLine($"'{formattedDateTimeString}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ProvisioningState), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" provisioningState: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ProvisioningState)) - { - builder.Append(" provisioningState: "); - if (ProvisioningState.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ProvisioningState}'''"); - } - else - { - builder.AppendLine($"'{ProvisioningState}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ExtendedLocation), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" extendedLocation: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ExtendedLocation)) - { - builder.Append(" extendedLocation: "); - BicepSerializationHelpers.AppendChildObject(builder, ExtendedLocation, options, 2, false, " extendedLocation: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(GenericResourceData)} does not support writing '{options.Format}' format."); - } - } - - GenericResourceData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeGenericResourceData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(GenericResourceData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/GenericResourceData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/GenericResourceData.cs deleted file mode 100644 index 1440e3dc01..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/GenericResourceData.cs +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the GenericResource data model. - /// Resource information. - /// - public partial class GenericResourceData : TrackedResourceExtendedData - { - /// Initializes a new instance of . - /// The location. - public GenericResourceData(AzureLocation location) : base(location) - { - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The tags. - /// The location. - /// Resource extended location. - /// Keeps track of any properties unknown to the library. - /// The plan of the resource. - /// The resource properties. - /// The kind of the resource. - /// ID of the resource that manages this resource. - /// The SKU of the resource. - /// The identity of the resource. - /// The created time of the resource. This is only present if requested via the $expand query parameter. - /// The changed time of the resource. This is only present if requested via the $expand query parameter. - /// The provisioning state of the resource. This is only present if requested via the $expand query parameter. - internal GenericResourceData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, IDictionary tags, AzureLocation location, ExtendedLocation extendedLocation, IDictionary serializedAdditionalRawData, ArmPlan plan, BinaryData properties, string kind, string managedBy, ResourcesSku sku, ManagedServiceIdentity identity, DateTimeOffset? createdOn, DateTimeOffset? changedOn, string provisioningState) : base(id, name, resourceType, systemData, tags, location, extendedLocation, serializedAdditionalRawData) - { - Plan = plan; - Properties = properties; - Kind = kind; - ManagedBy = managedBy; - Sku = sku; - Identity = identity; - CreatedOn = createdOn; - ChangedOn = changedOn; - ProvisioningState = provisioningState; - } - - /// Initializes a new instance of for deserialization. - internal GenericResourceData() - { - } - - /// The plan of the resource. - [WirePath("plan")] - public ArmPlan Plan { get; set; } - /// - /// The resource properties. - /// - /// To assign an object to this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("properties")] - public BinaryData Properties { get; set; } - /// The kind of the resource. - [WirePath("kind")] - public string Kind { get; set; } - /// ID of the resource that manages this resource. - [WirePath("managedBy")] - public string ManagedBy { get; set; } - /// The SKU of the resource. - [WirePath("sku")] - public ResourcesSku Sku { get; set; } - /// The identity of the resource. - [WirePath("identity")] - public ManagedServiceIdentity Identity { get; set; } - /// The created time of the resource. This is only present if requested via the $expand query parameter. - [WirePath("createdTime")] - public DateTimeOffset? CreatedOn { get; } - /// The changed time of the resource. This is only present if requested via the $expand query parameter. - [WirePath("changedTime")] - public DateTimeOffset? ChangedOn { get; } - /// The provisioning state of the resource. This is only present if requested via the $expand query parameter. - [WirePath("provisioningState")] - public string ProvisioningState { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Internal/Utf8JsonRequestContent.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Internal/Utf8JsonRequestContent.cs deleted file mode 100644 index c0ffe14923..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Internal/Utf8JsonRequestContent.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.IO; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; - -namespace Azure.ResourceManager -{ - internal class Utf8JsonRequestContent : RequestContent - { - private readonly MemoryStream _stream; - private readonly RequestContent _content; - - public Utf8JsonRequestContent() - { - _stream = new MemoryStream(); - _content = Create(_stream); - JsonWriter = new Utf8JsonWriter(_stream); - } - - public Utf8JsonWriter JsonWriter { get; } - - public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default) - { - await JsonWriter.FlushAsync().ConfigureAwait(false); - await _content.WriteToAsync(stream, cancellationToken).ConfigureAwait(false); - } - - public override void WriteTo(Stream stream, CancellationToken cancellationToken = default) - { - JsonWriter.Flush(); - _content.WriteTo(stream, cancellationToken); - } - - public override bool TryComputeLength(out long length) - { - length = JsonWriter.BytesCommitted + JsonWriter.BytesPending; - return true; - } - - public override void Dispose() - { - JsonWriter.Dispose(); - _content.Dispose(); - _stream.Dispose(); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Internal/WirePathAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Internal/WirePathAttribute.cs deleted file mode 100644 index 4b7cb3247b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Internal/WirePathAttribute.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.Resources -{ - [AttributeUsage(AttributeTargets.Property)] - internal class WirePathAttribute : Attribute - { - private string _wirePath; - - public WirePathAttribute(string wirePath) - { - _wirePath = wirePath; - } - - public override string ToString() - { - return _wirePath; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/GenericResourceOperationSource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/GenericResourceOperationSource.cs deleted file mode 100644 index f8b70fafa0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/GenericResourceOperationSource.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.ClientModel.Primitives; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; - -namespace Azure.ResourceManager.Resources -{ - internal class GenericResourceOperationSource : IOperationSource - { - private readonly ArmClient _client; - - internal GenericResourceOperationSource(ArmClient client) - { - _client = client; - } - - GenericResource IOperationSource.CreateResult(Response response, CancellationToken cancellationToken) - { - var data = ModelReaderWriter.Read(response.Content, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default); - return new GenericResource(_client, data); - } - - async ValueTask IOperationSource.CreateResultAsync(Response response, CancellationToken cancellationToken) - { - var data = ModelReaderWriter.Read(response.Content, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default); - return await Task.FromResult(new GenericResource(_client, data)).ConfigureAwait(false); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourceGroupExportResultOperationSource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourceGroupExportResultOperationSource.cs deleted file mode 100644 index a2603f1e90..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourceGroupExportResultOperationSource.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal class ResourceGroupExportResultOperationSource : IOperationSource - { - ResourceGroupExportResult IOperationSource.CreateResult(Response response, CancellationToken cancellationToken) - { - using var document = JsonDocument.Parse(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - return ResourceGroupExportResult.DeserializeResourceGroupExportResult(document.RootElement); - } - - async ValueTask IOperationSource.CreateResultAsync(Response response, CancellationToken cancellationToken) - { - using var document = await JsonDocument.ParseAsync(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - return ResourceGroupExportResult.DeserializeResourceGroupExportResult(document.RootElement); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourcesArmOperation.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourcesArmOperation.cs deleted file mode 100644 index f3162628f3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourcesArmOperation.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ -#pragma warning disable SA1649 // File name should match first type name - internal class ResourcesArmOperation : ArmOperation -#pragma warning restore SA1649 // File name should match first type name - { - private readonly OperationInternal _operation; - private readonly RehydrationToken? _completeRehydrationToken; - private readonly NextLinkOperationImplementation _nextLinkOperation; - private readonly string _operationId; - - /// Initializes a new instance of ResourcesArmOperation for mocking. - protected ResourcesArmOperation() - { - } - - internal ResourcesArmOperation(Response response, RehydrationToken? rehydrationToken = null) - { - _operation = OperationInternal.Succeeded(response); - _completeRehydrationToken = rehydrationToken; - _operationId = GetOperationId(rehydrationToken); - } - - internal ResourcesArmOperation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response, OperationFinalStateVia finalStateVia, bool skipApiVersionOverride = false, string apiVersionOverrideValue = null) - { - var nextLinkOperation = NextLinkOperationImplementation.Create(pipeline, request.Method, request.Uri.ToUri(), response, finalStateVia, skipApiVersionOverride, apiVersionOverrideValue); - if (nextLinkOperation is NextLinkOperationImplementation nextLinkOperationValue) - { - _nextLinkOperation = nextLinkOperationValue; - _operationId = _nextLinkOperation.OperationId; - } - else - { - _completeRehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(request.Method, request.Uri.ToUri(), response, finalStateVia); - _operationId = GetOperationId(_completeRehydrationToken); - } - _operation = new OperationInternal(nextLinkOperation, clientDiagnostics, response, "ResourcesArmOperation", fallbackStrategy: new SequentialDelayStrategy()); - } - - private string GetOperationId(RehydrationToken? rehydrationToken) - { - if (rehydrationToken is null) - { - return null; - } - var lroDetails = ModelReaderWriter.Write(rehydrationToken, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default).ToObjectFromJson>(); - return lroDetails["id"]; - } - /// - public override string Id => _operationId ?? NextLinkOperationImplementation.NotSet; - - /// - public override RehydrationToken? GetRehydrationToken() => _nextLinkOperation?.GetRehydrationToken() ?? _completeRehydrationToken; - - /// - public override bool HasCompleted => _operation.HasCompleted; - - /// - public override Response GetRawResponse() => _operation.RawResponse; - - /// - public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); - - /// - public override ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); - - /// - public override Response WaitForCompletionResponse(CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponse(cancellationToken); - - /// - public override Response WaitForCompletionResponse(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponse(pollingInterval, cancellationToken); - - /// - public override ValueTask WaitForCompletionResponseAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponseAsync(cancellationToken); - - /// - public override ValueTask WaitForCompletionResponseAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponseAsync(pollingInterval, cancellationToken); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourcesArmOperationOfT.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourcesArmOperationOfT.cs deleted file mode 100644 index eb320e40da..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourcesArmOperationOfT.cs +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ -#pragma warning disable SA1649 // File name should match first type name - internal class ResourcesArmOperation : ArmOperation -#pragma warning restore SA1649 // File name should match first type name - { - private readonly OperationInternal _operation; - private readonly RehydrationToken? _completeRehydrationToken; - private readonly NextLinkOperationImplementation _nextLinkOperation; - private readonly string _operationId; - - /// Initializes a new instance of ResourcesArmOperation for mocking. - protected ResourcesArmOperation() - { - } - - internal ResourcesArmOperation(Response response, RehydrationToken? rehydrationToken = null) - { - _operation = OperationInternal.Succeeded(response.GetRawResponse(), response.Value); - _completeRehydrationToken = rehydrationToken; - _operationId = GetOperationId(rehydrationToken); - } - - internal ResourcesArmOperation(IOperationSource source, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response, OperationFinalStateVia finalStateVia, bool skipApiVersionOverride = false, string apiVersionOverrideValue = null) - { - var nextLinkOperation = NextLinkOperationImplementation.Create(pipeline, request.Method, request.Uri.ToUri(), response, finalStateVia, skipApiVersionOverride, apiVersionOverrideValue); - if (nextLinkOperation is NextLinkOperationImplementation nextLinkOperationValue) - { - _nextLinkOperation = nextLinkOperationValue; - _operationId = _nextLinkOperation.OperationId; - } - else - { - _completeRehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(request.Method, request.Uri.ToUri(), response, finalStateVia); - _operationId = GetOperationId(_completeRehydrationToken); - } - _operation = new OperationInternal(NextLinkOperationImplementation.Create(source, nextLinkOperation), clientDiagnostics, response, "ResourcesArmOperation", fallbackStrategy: new SequentialDelayStrategy()); - } - - private string GetOperationId(RehydrationToken? rehydrationToken) - { - if (rehydrationToken is null) - { - return null; - } - var lroDetails = ModelReaderWriter.Write(rehydrationToken, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default).ToObjectFromJson>(); - return lroDetails["id"]; - } - /// - public override string Id => _operationId ?? NextLinkOperationImplementation.NotSet; - - /// - public override RehydrationToken? GetRehydrationToken() => _nextLinkOperation?.GetRehydrationToken() ?? _completeRehydrationToken; - - /// - public override T Value => _operation.Value; - - /// - public override bool HasValue => _operation.HasValue; - - /// - public override bool HasCompleted => _operation.HasCompleted; - - /// - public override Response GetRawResponse() => _operation.RawResponse; - - /// - public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); - - /// - public override ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); - - /// - public override Response WaitForCompletion(CancellationToken cancellationToken = default) => _operation.WaitForCompletion(cancellationToken); - - /// - public override Response WaitForCompletion(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletion(pollingInterval, cancellationToken); - - /// - public override ValueTask> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken); - - /// - public override ValueTask> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/TagResourceOperationSource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/TagResourceOperationSource.cs deleted file mode 100644 index 452c0702a4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/TagResourceOperationSource.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.ClientModel.Primitives; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; - -namespace Azure.ResourceManager.Resources -{ - internal class TagResourceOperationSource : IOperationSource - { - private readonly ArmClient _client; - - internal TagResourceOperationSource(ArmClient client) - { - _client = client; - } - - TagResource IOperationSource.CreateResult(Response response, CancellationToken cancellationToken) - { - var data = ModelReaderWriter.Read(response.Content, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default); - return new TagResource(_client, data); - } - - async ValueTask IOperationSource.CreateResultAsync(Response response, CancellationToken cancellationToken) - { - var data = ModelReaderWriter.Read(response.Content, ModelReaderWriterOptions.Json, AzureResourceManagerContext.Default); - return await Task.FromResult(new TagResource(_client, data)).ConfigureAwait(false); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionCollection.cs deleted file mode 100644 index a11c7b1d4d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionCollection.cs +++ /dev/null @@ -1,501 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetManagementGroupPolicyDefinitions method from an instance of . - /// - public partial class ManagementGroupPolicyDefinitionCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics; - private readonly PolicyDefinitionsRestOperations _managementGroupPolicyDefinitionPolicyDefinitionsRestClient; - - /// Initializes a new instance of the class for mocking. - protected ManagementGroupPolicyDefinitionCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal ManagementGroupPolicyDefinitionCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ManagementGroupPolicyDefinitionResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ManagementGroupPolicyDefinitionResource.ResourceType, out string managementGroupPolicyDefinitionPolicyDefinitionsApiVersion); - _managementGroupPolicyDefinitionPolicyDefinitionsRestClient = new PolicyDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementGroupPolicyDefinitionPolicyDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ManagementGroupResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ManagementGroupResource.ResourceType), nameof(id)); - } - - /// - /// This operation creates or updates a policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_CreateOrUpdateAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy definition to create. - /// The policy definition properties. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string policyDefinitionName, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateOrUpdateAtManagementGroupAsync(Id.Name, policyDefinitionName, data, cancellationToken).ConfigureAwait(false); - var uri = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateCreateOrUpdateAtManagementGroupRequestUri(Id.Name, policyDefinitionName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_CreateOrUpdateAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy definition to create. - /// The policy definition properties. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string policyDefinitionName, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateOrUpdateAtManagementGroup(Id.Name, policyDefinitionName, data, cancellationToken); - var uri = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateCreateOrUpdateAtManagementGroupRequestUri(Id.Name, policyDefinitionName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionCollection.Get"); - scope.Start(); - try - { - var response = await _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.GetAtManagementGroupAsync(Id.Name, policyDefinitionName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionCollection.Get"); - scope.Start(); - try - { - var response = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.GetAtManagementGroup(Id.Name, policyDefinitionName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a list of all the policy definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions - /// - /// - /// Operation Id - /// PolicyDefinitions_ListByManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateListByManagementGroupRequest(Id.Name, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateListByManagementGroupNextPageRequest(nextLink, Id.Name, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new ManagementGroupPolicyDefinitionResource(Client, PolicyDefinitionData.DeserializePolicyDefinitionData(e)), _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics, Pipeline, "ManagementGroupPolicyDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// This operation retrieves a list of all the policy definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions - /// - /// - /// Operation Id - /// PolicyDefinitions_ListByManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateListByManagementGroupRequest(Id.Name, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateListByManagementGroupNextPageRequest(nextLink, Id.Name, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new ManagementGroupPolicyDefinitionResource(Client, PolicyDefinitionData.DeserializePolicyDefinitionData(e)), _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics, Pipeline, "ManagementGroupPolicyDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = await _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.GetAtManagementGroupAsync(Id.Name, policyDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.GetAtManagementGroup(Id.Name, policyDefinitionName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.GetAtManagementGroupAsync(Id.Name, policyDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.GetAtManagementGroup(Id.Name, policyDefinitionName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionResource.Serialization.cs deleted file mode 100644 index 867c419838..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class ManagementGroupPolicyDefinitionResource : IJsonModel - { - private static PolicyDefinitionData s_dataDeserializationInstance; - private static PolicyDefinitionData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - PolicyDefinitionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - PolicyDefinitionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionResource.cs deleted file mode 100644 index f254f2ed5e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionResource.cs +++ /dev/null @@ -1,354 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a ManagementGroupPolicyDefinition along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetManagementGroupPolicyDefinitionResource method. - /// Otherwise you can get one from its parent resource using the GetManagementGroupPolicyDefinition method. - /// - public partial class ManagementGroupPolicyDefinitionResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The managementGroupId. - /// The policyDefinitionName. - public static ResourceIdentifier CreateResourceIdentifier(string managementGroupId, string policyDefinitionName) - { - var resourceId = $"/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics; - private readonly PolicyDefinitionsRestOperations _managementGroupPolicyDefinitionPolicyDefinitionsRestClient; - private readonly PolicyDefinitionData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Authorization/policyDefinitions"; - - /// Initializes a new instance of the class for mocking. - protected ManagementGroupPolicyDefinitionResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal ManagementGroupPolicyDefinitionResource(ArmClient client, PolicyDefinitionData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal ManagementGroupPolicyDefinitionResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string managementGroupPolicyDefinitionPolicyDefinitionsApiVersion); - _managementGroupPolicyDefinitionPolicyDefinitionsRestClient = new PolicyDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementGroupPolicyDefinitionPolicyDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual PolicyDefinitionData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionResource.Get"); - scope.Start(); - try - { - var response = await _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.GetAtManagementGroupAsync(Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionResource.Get"); - scope.Start(); - try - { - var response = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.GetAtManagementGroup(Id.Parent.Name, Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes the policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_DeleteAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual async Task DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionResource.Delete"); - scope.Start(); - try - { - var response = await _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.DeleteAtManagementGroupAsync(Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); - var uri = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateDeleteAtManagementGroupRequestUri(Id.Parent.Name, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes the policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_DeleteAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionResource.Delete"); - scope.Start(); - try - { - var response = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.DeleteAtManagementGroup(Id.Parent.Name, Id.Name, cancellationToken); - var uri = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateDeleteAtManagementGroupRequestUri(Id.Parent.Name, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_CreateOrUpdateAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The policy definition properties. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(WaitUntil waitUntil, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionResource.Update"); - scope.Start(); - try - { - var response = await _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateOrUpdateAtManagementGroupAsync(Id.Parent.Name, Id.Name, data, cancellationToken).ConfigureAwait(false); - var uri = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateCreateOrUpdateAtManagementGroupRequestUri(Id.Parent.Name, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_CreateOrUpdateAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The policy definition properties. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation Update(WaitUntil waitUntil, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementGroupPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicyDefinitionResource.Update"); - scope.Start(); - try - { - var response = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateOrUpdateAtManagementGroup(Id.Parent.Name, Id.Name, data, cancellationToken); - var uri = _managementGroupPolicyDefinitionPolicyDefinitionsRestClient.CreateCreateOrUpdateAtManagementGroupRequestUri(Id.Parent.Name, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementGroupPolicyDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionCollection.cs deleted file mode 100644 index e556e58ffa..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionCollection.cs +++ /dev/null @@ -1,501 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetManagementGroupPolicySetDefinitions method from an instance of . - /// - public partial class ManagementGroupPolicySetDefinitionCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics; - private readonly PolicySetDefinitionsRestOperations _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient; - - /// Initializes a new instance of the class for mocking. - protected ManagementGroupPolicySetDefinitionCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal ManagementGroupPolicySetDefinitionCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ManagementGroupPolicySetDefinitionResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ManagementGroupPolicySetDefinitionResource.ResourceType, out string managementGroupPolicySetDefinitionPolicySetDefinitionsApiVersion); - _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient = new PolicySetDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementGroupPolicySetDefinitionPolicySetDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ManagementGroupResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ManagementGroupResource.ResourceType), nameof(id)); - } - - /// - /// This operation creates or updates a policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_CreateOrUpdateAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy set definition to create. - /// The policy set definition properties. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string policySetDefinitionName, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateOrUpdateAtManagementGroupAsync(Id.Name, policySetDefinitionName, data, cancellationToken).ConfigureAwait(false); - var uri = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateCreateOrUpdateAtManagementGroupRequestUri(Id.Name, policySetDefinitionName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_CreateOrUpdateAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy set definition to create. - /// The policy set definition properties. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string policySetDefinitionName, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateOrUpdateAtManagementGroup(Id.Name, policySetDefinitionName, data, cancellationToken); - var uri = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateCreateOrUpdateAtManagementGroupRequestUri(Id.Name, policySetDefinitionName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionCollection.Get"); - scope.Start(); - try - { - var response = await _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.GetAtManagementGroupAsync(Id.Name, policySetDefinitionName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionCollection.Get"); - scope.Start(); - try - { - var response = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.GetAtManagementGroup(Id.Name, policySetDefinitionName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a list of all the policy set definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions - /// - /// - /// Operation Id - /// PolicySetDefinitions_ListByManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListByManagementGroupRequest(Id.Name, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListByManagementGroupNextPageRequest(nextLink, Id.Name, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new ManagementGroupPolicySetDefinitionResource(Client, PolicySetDefinitionData.DeserializePolicySetDefinitionData(e)), _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics, Pipeline, "ManagementGroupPolicySetDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// This operation retrieves a list of all the policy set definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions - /// - /// - /// Operation Id - /// PolicySetDefinitions_ListByManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListByManagementGroupRequest(Id.Name, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListByManagementGroupNextPageRequest(nextLink, Id.Name, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new ManagementGroupPolicySetDefinitionResource(Client, PolicySetDefinitionData.DeserializePolicySetDefinitionData(e)), _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics, Pipeline, "ManagementGroupPolicySetDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = await _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.GetAtManagementGroupAsync(Id.Name, policySetDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.GetAtManagementGroup(Id.Name, policySetDefinitionName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.GetAtManagementGroupAsync(Id.Name, policySetDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.GetAtManagementGroup(Id.Name, policySetDefinitionName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionResource.Serialization.cs deleted file mode 100644 index 60c244d59e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class ManagementGroupPolicySetDefinitionResource : IJsonModel - { - private static PolicySetDefinitionData s_dataDeserializationInstance; - private static PolicySetDefinitionData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - PolicySetDefinitionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - PolicySetDefinitionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionResource.cs deleted file mode 100644 index 4f8ffed49d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionResource.cs +++ /dev/null @@ -1,354 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a ManagementGroupPolicySetDefinition along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetManagementGroupPolicySetDefinitionResource method. - /// Otherwise you can get one from its parent resource using the GetManagementGroupPolicySetDefinition method. - /// - public partial class ManagementGroupPolicySetDefinitionResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The managementGroupId. - /// The policySetDefinitionName. - public static ResourceIdentifier CreateResourceIdentifier(string managementGroupId, string policySetDefinitionName) - { - var resourceId = $"/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics; - private readonly PolicySetDefinitionsRestOperations _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient; - private readonly PolicySetDefinitionData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Authorization/policySetDefinitions"; - - /// Initializes a new instance of the class for mocking. - protected ManagementGroupPolicySetDefinitionResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal ManagementGroupPolicySetDefinitionResource(ArmClient client, PolicySetDefinitionData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal ManagementGroupPolicySetDefinitionResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string managementGroupPolicySetDefinitionPolicySetDefinitionsApiVersion); - _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient = new PolicySetDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementGroupPolicySetDefinitionPolicySetDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual PolicySetDefinitionData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionResource.Get"); - scope.Start(); - try - { - var response = await _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.GetAtManagementGroupAsync(Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionResource.Get"); - scope.Start(); - try - { - var response = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.GetAtManagementGroup(Id.Parent.Name, Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes the policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_DeleteAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual async Task DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionResource.Delete"); - scope.Start(); - try - { - var response = await _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.DeleteAtManagementGroupAsync(Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); - var uri = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateDeleteAtManagementGroupRequestUri(Id.Parent.Name, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes the policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_DeleteAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionResource.Delete"); - scope.Start(); - try - { - var response = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.DeleteAtManagementGroup(Id.Parent.Name, Id.Name, cancellationToken); - var uri = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateDeleteAtManagementGroupRequestUri(Id.Parent.Name, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_CreateOrUpdateAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The policy set definition properties. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(WaitUntil waitUntil, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionResource.Update"); - scope.Start(); - try - { - var response = await _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateOrUpdateAtManagementGroupAsync(Id.Parent.Name, Id.Name, data, cancellationToken).ConfigureAwait(false); - var uri = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateCreateOrUpdateAtManagementGroupRequestUri(Id.Parent.Name, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy set definition in the given management group with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_CreateOrUpdateAtManagementGroup - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The policy set definition properties. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation Update(WaitUntil waitUntil, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementGroupPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("ManagementGroupPolicySetDefinitionResource.Update"); - scope.Start(); - try - { - var response = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateOrUpdateAtManagementGroup(Id.Parent.Name, Id.Name, data, cancellationToken); - var uri = _managementGroupPolicySetDefinitionPolicySetDefinitionsRestClient.CreateCreateOrUpdateAtManagementGroupRequestUri(Id.Parent.Name, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementGroupPolicySetDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockCollection.cs deleted file mode 100644 index bb744b2095..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockCollection.cs +++ /dev/null @@ -1,488 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetManagementLocks method from an instance of . - /// - public partial class ManagementLockCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _managementLockClientDiagnostics; - private readonly ManagementLocksRestOperations _managementLockRestClient; - - /// Initializes a new instance of the class for mocking. - protected ManagementLockCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal ManagementLockCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementLockClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ManagementLockResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ManagementLockResource.ResourceType, out string managementLockApiVersion); - _managementLockRestClient = new ManagementLocksRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementLockApiVersion); - } - - /// - /// Create or update a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_CreateOrUpdateByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of lock. - /// Create or update management lock parameters. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string lockName, ManagementLockData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _managementLockRestClient.CreateOrUpdateByScopeAsync(Id, lockName, data, cancellationToken).ConfigureAwait(false); - var uri = _managementLockRestClient.CreateCreateOrUpdateByScopeRequestUri(Id, lockName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementLockResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Create or update a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_CreateOrUpdateByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of lock. - /// Create or update management lock parameters. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string lockName, ManagementLockData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = _managementLockRestClient.CreateOrUpdateByScope(Id, lockName, data, cancellationToken); - var uri = _managementLockRestClient.CreateCreateOrUpdateByScopeRequestUri(Id, lockName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementLockResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Get a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of lock. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockCollection.Get"); - scope.Start(); - try - { - var response = await _managementLockRestClient.GetByScopeAsync(Id, lockName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementLockResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Get a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of lock. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockCollection.Get"); - scope.Start(); - try - { - var response = _managementLockRestClient.GetByScope(Id, lockName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementLockResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets all the management locks for a scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks - /// - /// - /// Operation Id - /// ManagementLocks_ListByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementLockRestClient.CreateListByScopeRequest(Id, filter); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementLockRestClient.CreateListByScopeNextPageRequest(nextLink, Id, filter); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new ManagementLockResource(Client, ManagementLockData.DeserializeManagementLockData(e)), _managementLockClientDiagnostics, Pipeline, "ManagementLockCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Gets all the management locks for a scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks - /// - /// - /// Operation Id - /// ManagementLocks_ListByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _managementLockRestClient.CreateListByScopeRequest(Id, filter); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _managementLockRestClient.CreateListByScopeNextPageRequest(nextLink, Id, filter); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new ManagementLockResource(Client, ManagementLockData.DeserializeManagementLockData(e)), _managementLockClientDiagnostics, Pipeline, "ManagementLockCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of lock. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockCollection.Exists"); - scope.Start(); - try - { - var response = await _managementLockRestClient.GetByScopeAsync(Id, lockName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of lock. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockCollection.Exists"); - scope.Start(); - try - { - var response = _managementLockRestClient.GetByScope(Id, lockName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of lock. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _managementLockRestClient.GetByScopeAsync(Id, lockName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementLockResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of lock. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockCollection.GetIfExists"); - scope.Start(); - try - { - var response = _managementLockRestClient.GetByScope(Id, lockName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ManagementLockResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockData.Serialization.cs deleted file mode 100644 index 1468da3f30..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockData.Serialization.cs +++ /dev/null @@ -1,334 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class ManagementLockData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementLockData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - writer.WritePropertyName("level"u8); - writer.WriteStringValue(Level.ToString()); - if (Optional.IsDefined(Notes)) - { - writer.WritePropertyName("notes"u8); - writer.WriteStringValue(Notes); - } - if (Optional.IsCollectionDefined(Owners)) - { - writer.WritePropertyName("owners"u8); - writer.WriteStartArray(); - foreach (var item in Owners) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - writer.WriteEndObject(); - } - - ManagementLockData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementLockData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementLockData(document.RootElement, options); - } - - internal static ManagementLockData DeserializeManagementLockData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - ManagementLockLevel level = default; - string notes = default; - IList owners = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("level"u8)) - { - level = new ManagementLockLevel(property0.Value.GetString()); - continue; - } - if (property0.NameEquals("notes"u8)) - { - notes = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("owners"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(ManagementLockOwner.DeserializeManagementLockOwner(item, options)); - } - owners = array; - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementLockData( - id, - name, - type, - systemData, - level, - notes, - owners ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.Append(" properties:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Level), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" level: "); - builder.AppendLine(propertyOverride); - } - else - { - builder.Append(" level: "); - builder.AppendLine($"'{Level.ToString()}'"); - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Notes), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" notes: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Notes)) - { - builder.Append(" notes: "); - if (Notes.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Notes}'''"); - } - else - { - builder.AppendLine($"'{Notes}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Owners), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" owners: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Owners)) - { - if (Owners.Any()) - { - builder.Append(" owners: "); - builder.AppendLine("["); - foreach (var item in Owners) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 6, true, " owners: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine(" }"); - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementLockData)} does not support writing '{options.Format}' format."); - } - } - - ManagementLockData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementLockData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementLockData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockData.cs deleted file mode 100644 index 64c9e5d2cd..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockData.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the ManagementLock data model. - /// The lock information. - /// - public partial class ManagementLockData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The level of the lock. Possible values are: NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users are able to read and modify the resources, but not delete. ReadOnly means authorized users can only read from a resource, but they can't modify or delete it. - public ManagementLockData(ManagementLockLevel level) - { - Level = level; - Owners = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The level of the lock. Possible values are: NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users are able to read and modify the resources, but not delete. ReadOnly means authorized users can only read from a resource, but they can't modify or delete it. - /// Notes about the lock. Maximum of 512 characters. - /// The owners of the lock. - /// Keeps track of any properties unknown to the library. - internal ManagementLockData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, ManagementLockLevel level, string notes, IList owners, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - Level = level; - Notes = notes; - Owners = owners; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal ManagementLockData() - { - } - - /// The level of the lock. Possible values are: NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users are able to read and modify the resources, but not delete. ReadOnly means authorized users can only read from a resource, but they can't modify or delete it. - [WirePath("properties.level")] - public ManagementLockLevel Level { get; set; } - /// Notes about the lock. Maximum of 512 characters. - [WirePath("properties.notes")] - public string Notes { get; set; } - /// The owners of the lock. - [WirePath("properties.owners")] - public IList Owners { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockResource.Serialization.cs deleted file mode 100644 index 3dfbf0b23b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class ManagementLockResource : IJsonModel - { - private static ManagementLockData s_dataDeserializationInstance; - private static ManagementLockData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - ManagementLockData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - ManagementLockData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockResource.cs deleted file mode 100644 index e02de890dd..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ManagementLockResource.cs +++ /dev/null @@ -1,353 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a ManagementLock along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetManagementLockResource method. - /// Otherwise you can get one from its parent resource using the GetManagementLock method. - /// - public partial class ManagementLockResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The scope. - /// The lockName. - public static ResourceIdentifier CreateResourceIdentifier(string scope, string lockName) - { - var resourceId = $"{scope}/providers/Microsoft.Authorization/locks/{lockName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _managementLockClientDiagnostics; - private readonly ManagementLocksRestOperations _managementLockRestClient; - private readonly ManagementLockData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Authorization/locks"; - - /// Initializes a new instance of the class for mocking. - protected ManagementLockResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal ManagementLockResource(ArmClient client, ManagementLockData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal ManagementLockResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _managementLockClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string managementLockApiVersion); - _managementLockRestClient = new ManagementLocksRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, managementLockApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual ManagementLockData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// Get a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockResource.Get"); - scope.Start(); - try - { - var response = await _managementLockRestClient.GetByScopeAsync(Id.Parent, Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementLockResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Get a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_GetByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockResource.Get"); - scope.Start(); - try - { - var response = _managementLockRestClient.GetByScope(Id.Parent, Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ManagementLockResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Delete a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_DeleteByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual async Task DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockResource.Delete"); - scope.Start(); - try - { - var response = await _managementLockRestClient.DeleteByScopeAsync(Id.Parent, Id.Name, cancellationToken).ConfigureAwait(false); - var uri = _managementLockRestClient.CreateDeleteByScopeRequestUri(Id.Parent, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Delete a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_DeleteByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockResource.Delete"); - scope.Start(); - try - { - var response = _managementLockRestClient.DeleteByScope(Id.Parent, Id.Name, cancellationToken); - var uri = _managementLockRestClient.CreateDeleteByScopeRequestUri(Id.Parent, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Create or update a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_CreateOrUpdateByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Create or update management lock parameters. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(WaitUntil waitUntil, ManagementLockData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockResource.Update"); - scope.Start(); - try - { - var response = await _managementLockRestClient.CreateOrUpdateByScopeAsync(Id.Parent, Id.Name, data, cancellationToken).ConfigureAwait(false); - var uri = _managementLockRestClient.CreateCreateOrUpdateByScopeRequestUri(Id.Parent, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementLockResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Create or update a management lock by scope. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/locks/{lockName} - /// - /// - /// Operation Id - /// ManagementLocks_CreateOrUpdateByScope - /// - /// - /// Default Api Version - /// 2020-05-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Create or update management lock parameters. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation Update(WaitUntil waitUntil, ManagementLockData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _managementLockClientDiagnostics.CreateScope("ManagementLockResource.Update"); - scope.Start(); - try - { - var response = _managementLockRestClient.CreateOrUpdateByScope(Id.Parent, Id.Name, data, cancellationToken); - var uri = _managementLockRestClient.CreateCreateOrUpdateByScopeRequestUri(Id.Parent, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ManagementLockResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ApiProfile.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ApiProfile.Serialization.cs deleted file mode 100644 index e10abbf84b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ApiProfile.Serialization.cs +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ApiProfile : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ApiProfile)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(ProfileVersion)) - { - writer.WritePropertyName("profileVersion"u8); - writer.WriteStringValue(ProfileVersion); - } - if (options.Format != "W" && Optional.IsDefined(ApiVersion)) - { - writer.WritePropertyName("apiVersion"u8); - writer.WriteStringValue(ApiVersion); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ApiProfile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ApiProfile)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeApiProfile(document.RootElement, options); - } - - internal static ApiProfile DeserializeApiProfile(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string profileVersion = default; - string apiVersion = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("profileVersion"u8)) - { - profileVersion = property.Value.GetString(); - continue; - } - if (property.NameEquals("apiVersion"u8)) - { - apiVersion = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ApiProfile(profileVersion, apiVersion, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ProfileVersion), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" profileVersion: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ProfileVersion)) - { - builder.Append(" profileVersion: "); - if (ProfileVersion.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ProfileVersion}'''"); - } - else - { - builder.AppendLine($"'{ProfileVersion}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ApiVersion), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" apiVersion: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ApiVersion)) - { - builder.Append(" apiVersion: "); - if (ApiVersion.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ApiVersion}'''"); - } - else - { - builder.AppendLine($"'{ApiVersion}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ApiProfile)} does not support writing '{options.Format}' format."); - } - } - - ApiProfile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeApiProfile(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ApiProfile)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ApiProfile.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ApiProfile.cs deleted file mode 100644 index f739455520..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ApiProfile.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The ApiProfile. - public partial class ApiProfile - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ApiProfile() - { - } - - /// Initializes a new instance of . - /// The profile version. - /// The API version. - /// Keeps track of any properties unknown to the library. - internal ApiProfile(string profileVersion, string apiVersion, IDictionary serializedAdditionalRawData) - { - ProfileVersion = profileVersion; - ApiVersion = apiVersion; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The profile version. - [WirePath("profileVersion")] - public string ProfileVersion { get; } - /// The API version. - [WirePath("apiVersion")] - public string ApiVersion { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameter.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameter.Serialization.cs deleted file mode 100644 index 8c48aed370..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameter.Serialization.cs +++ /dev/null @@ -1,306 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ArmPolicyParameter : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmPolicyParameter)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(ParameterType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ParameterType.Value.ToString()); - } - if (Optional.IsCollectionDefined(AllowedValues)) - { - writer.WritePropertyName("allowedValues"u8); - writer.WriteStartArray(); - foreach (var item in AllowedValues) - { - if (item == null) - { - writer.WriteNullValue(); - continue; - } -#if NET6_0_OR_GREATER - writer.WriteRawValue(item); -#else - using (JsonDocument document = JsonDocument.Parse(item, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(DefaultValue)) - { - writer.WritePropertyName("defaultValue"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(DefaultValue); -#else - using (JsonDocument document = JsonDocument.Parse(DefaultValue, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - if (Optional.IsDefined(Metadata)) - { - writer.WritePropertyName("metadata"u8); - writer.WriteObjectValue(Metadata, options); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ArmPolicyParameter IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmPolicyParameter)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeArmPolicyParameter(document.RootElement, options); - } - - internal static ArmPolicyParameter DeserializeArmPolicyParameter(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ArmPolicyParameterType? type = default; - IList allowedValues = default; - BinaryData defaultValue = default; - ParameterDefinitionsValueMetadata metadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = new ArmPolicyParameterType(property.Value.GetString()); - continue; - } - if (property.NameEquals("allowedValues"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - if (item.ValueKind == JsonValueKind.Null) - { - array.Add(null); - } - else - { - array.Add(BinaryData.FromString(item.GetRawText())); - } - } - allowedValues = array; - continue; - } - if (property.NameEquals("defaultValue"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - defaultValue = BinaryData.FromString(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("metadata"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - metadata = ParameterDefinitionsValueMetadata.DeserializeParameterDefinitionsValueMetadata(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ArmPolicyParameter(type, allowedValues ?? new ChangeTrackingList(), defaultValue, metadata, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ParameterType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" type: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ParameterType)) - { - builder.Append(" type: "); - builder.AppendLine($"'{ParameterType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(AllowedValues), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" allowedValues: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(AllowedValues)) - { - if (AllowedValues.Any()) - { - builder.Append(" allowedValues: "); - builder.AppendLine("["); - foreach (var item in AllowedValues) - { - if (item == null) - { - builder.Append("null"); - continue; - } - builder.AppendLine($" '{item.ToString()}'"); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DefaultValue), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" defaultValue: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DefaultValue)) - { - builder.Append(" defaultValue: "); - builder.AppendLine($"'{DefaultValue.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Metadata), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" metadata: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Metadata)) - { - builder.Append(" metadata: "); - BicepSerializationHelpers.AppendChildObject(builder, Metadata, options, 2, false, " metadata: "); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ArmPolicyParameter)} does not support writing '{options.Format}' format."); - } - } - - ArmPolicyParameter IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeArmPolicyParameter(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ArmPolicyParameter)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameter.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameter.cs deleted file mode 100644 index 9eb8280256..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameter.cs +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The definition of a parameter that can be provided to the policy. - public partial class ArmPolicyParameter - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ArmPolicyParameter() - { - AllowedValues = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The data type of the parameter. - /// The allowed values for the parameter. - /// The default value for the parameter if no value is provided. - /// General metadata for the parameter. - /// Keeps track of any properties unknown to the library. - internal ArmPolicyParameter(ArmPolicyParameterType? parameterType, IList allowedValues, BinaryData defaultValue, ParameterDefinitionsValueMetadata metadata, IDictionary serializedAdditionalRawData) - { - ParameterType = parameterType; - AllowedValues = allowedValues; - DefaultValue = defaultValue; - Metadata = metadata; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The data type of the parameter. - [WirePath("type")] - public ArmPolicyParameterType? ParameterType { get; set; } - /// - /// The allowed values for the parameter. - /// - /// To assign an object to the element of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("allowedValues")] - public IList AllowedValues { get; } - /// - /// The default value for the parameter if no value is provided. - /// - /// To assign an object to this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("defaultValue")] - public BinaryData DefaultValue { get; set; } - /// General metadata for the parameter. - [WirePath("metadata")] - public ParameterDefinitionsValueMetadata Metadata { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterType.cs deleted file mode 100644 index c0dee9c68a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterType.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The data type of the parameter. - public readonly partial struct ArmPolicyParameterType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ArmPolicyParameterType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string StringValue = "String"; - private const string ArrayValue = "Array"; - private const string ObjectValue = "Object"; - private const string BooleanValue = "Boolean"; - private const string IntegerValue = "Integer"; - private const string FloatValue = "Float"; - private const string DateTimeValue = "DateTime"; - - /// String. - public static ArmPolicyParameterType String { get; } = new ArmPolicyParameterType(StringValue); - /// Array. - public static ArmPolicyParameterType Array { get; } = new ArmPolicyParameterType(ArrayValue); - /// Object. - public static ArmPolicyParameterType Object { get; } = new ArmPolicyParameterType(ObjectValue); - /// Boolean. - public static ArmPolicyParameterType Boolean { get; } = new ArmPolicyParameterType(BooleanValue); - /// Integer. - public static ArmPolicyParameterType Integer { get; } = new ArmPolicyParameterType(IntegerValue); - /// Float. - public static ArmPolicyParameterType Float { get; } = new ArmPolicyParameterType(FloatValue); - /// DateTime. - public static ArmPolicyParameterType DateTime { get; } = new ArmPolicyParameterType(DateTimeValue); - /// Determines if two values are the same. - public static bool operator ==(ArmPolicyParameterType left, ArmPolicyParameterType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ArmPolicyParameterType left, ArmPolicyParameterType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ArmPolicyParameterType(string value) => new ArmPolicyParameterType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ArmPolicyParameterType other && Equals(other); - /// - public bool Equals(ArmPolicyParameterType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterValue.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterValue.Serialization.cs deleted file mode 100644 index 2612dbb29e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterValue.Serialization.cs +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ArmPolicyParameterValue : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmPolicyParameterValue)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Value)) - { - writer.WritePropertyName("value"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(Value); -#else - using (JsonDocument document = JsonDocument.Parse(Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ArmPolicyParameterValue IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ArmPolicyParameterValue)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeArmPolicyParameterValue(document.RootElement, options); - } - - internal static ArmPolicyParameterValue DeserializeArmPolicyParameterValue(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - BinaryData value = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - value = BinaryData.FromString(property.Value.GetRawText()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ArmPolicyParameterValue(value, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Value)) - { - builder.Append(" value: "); - builder.AppendLine($"'{Value.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ArmPolicyParameterValue)} does not support writing '{options.Format}' format."); - } - } - - ArmPolicyParameterValue IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeArmPolicyParameterValue(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ArmPolicyParameterValue)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterValue.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterValue.cs deleted file mode 100644 index 0e055d7eb1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterValue.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The value of a parameter. - public partial class ArmPolicyParameterValue - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ArmPolicyParameterValue() - { - } - - /// Initializes a new instance of . - /// The value of the parameter. - /// Keeps track of any properties unknown to the library. - internal ArmPolicyParameterValue(BinaryData value, IDictionary serializedAdditionalRawData) - { - Value = value; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// - /// The value of the parameter. - /// - /// To assign an object to this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("value")] - public BinaryData Value { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/AvailabilityZoneMappings.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/AvailabilityZoneMappings.Serialization.cs deleted file mode 100644 index ac779501aa..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/AvailabilityZoneMappings.Serialization.cs +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class AvailabilityZoneMappings : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AvailabilityZoneMappings)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(LogicalZone)) - { - writer.WritePropertyName("logicalZone"u8); - writer.WriteStringValue(LogicalZone); - } - if (options.Format != "W" && Optional.IsDefined(PhysicalZone)) - { - writer.WritePropertyName("physicalZone"u8); - writer.WriteStringValue(PhysicalZone); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - AvailabilityZoneMappings IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AvailabilityZoneMappings)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAvailabilityZoneMappings(document.RootElement, options); - } - - internal static AvailabilityZoneMappings DeserializeAvailabilityZoneMappings(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string logicalZone = default; - string physicalZone = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("logicalZone"u8)) - { - logicalZone = property.Value.GetString(); - continue; - } - if (property.NameEquals("physicalZone"u8)) - { - physicalZone = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new AvailabilityZoneMappings(logicalZone, physicalZone, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(LogicalZone), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" logicalZone: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(LogicalZone)) - { - builder.Append(" logicalZone: "); - if (LogicalZone.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{LogicalZone}'''"); - } - else - { - builder.AppendLine($"'{LogicalZone}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PhysicalZone), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" physicalZone: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PhysicalZone)) - { - builder.Append(" physicalZone: "); - if (PhysicalZone.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{PhysicalZone}'''"); - } - else - { - builder.AppendLine($"'{PhysicalZone}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(AvailabilityZoneMappings)} does not support writing '{options.Format}' format."); - } - } - - AvailabilityZoneMappings IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeAvailabilityZoneMappings(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(AvailabilityZoneMappings)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/AvailabilityZoneMappings.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/AvailabilityZoneMappings.cs deleted file mode 100644 index 98f10092e5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/AvailabilityZoneMappings.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Availability zone mappings for the region. - public partial class AvailabilityZoneMappings - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal AvailabilityZoneMappings() - { - } - - /// Initializes a new instance of . - /// The logical zone id for the availability zone. - /// The fully qualified physical zone id of availability zone to which logical zone id is mapped to. - /// Keeps track of any properties unknown to the library. - internal AvailabilityZoneMappings(string logicalZone, string physicalZone, IDictionary serializedAdditionalRawData) - { - LogicalZone = logicalZone; - PhysicalZone = physicalZone; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The logical zone id for the availability zone. - [WirePath("logicalZone")] - public string LogicalZone { get; } - /// The fully qualified physical zone id of availability zone to which logical zone id is mapped to. - [WirePath("physicalZone")] - public string PhysicalZone { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/AzureRoleDefinition.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/AzureRoleDefinition.Serialization.cs deleted file mode 100644 index e62dc5dae7..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/AzureRoleDefinition.Serialization.cs +++ /dev/null @@ -1,351 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class AzureRoleDefinition : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AzureRoleDefinition)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(IsServiceRole)) - { - writer.WritePropertyName("isServiceRole"u8); - writer.WriteBooleanValue(IsServiceRole.Value); - } - if (Optional.IsCollectionDefined(Permissions)) - { - writer.WritePropertyName("permissions"u8); - writer.WriteStartArray(); - foreach (var item in Permissions) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(Scopes)) - { - writer.WritePropertyName("scopes"u8); - writer.WriteStartArray(); - foreach (var item in Scopes) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - AzureRoleDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AzureRoleDefinition)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAzureRoleDefinition(document.RootElement, options); - } - - internal static AzureRoleDefinition DeserializeAzureRoleDefinition(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string id = default; - string name = default; - bool? isServiceRole = default; - IReadOnlyList permissions = default; - IReadOnlyList scopes = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("isServiceRole"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - isServiceRole = property.Value.GetBoolean(); - continue; - } - if (property.NameEquals("permissions"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(Permission.DeserializePermission(item, options)); - } - permissions = array; - continue; - } - if (property.NameEquals("scopes"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - scopes = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new AzureRoleDefinition( - id, - name, - isServiceRole, - permissions ?? new ChangeTrackingList(), - scopes ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - if (Id.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Id}'''"); - } - else - { - builder.AppendLine($"'{Id}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(IsServiceRole), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" isServiceRole: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(IsServiceRole)) - { - builder.Append(" isServiceRole: "); - var boolValue = IsServiceRole.Value == true ? "true" : "false"; - builder.AppendLine($"{boolValue}"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Permissions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" permissions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Permissions)) - { - if (Permissions.Any()) - { - builder.Append(" permissions: "); - builder.AppendLine("["); - foreach (var item in Permissions) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " permissions: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Scopes), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" scopes: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Scopes)) - { - if (Scopes.Any()) - { - builder.Append(" scopes: "); - builder.AppendLine("["); - foreach (var item in Scopes) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(AzureRoleDefinition)} does not support writing '{options.Format}' format."); - } - } - - AzureRoleDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeAzureRoleDefinition(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(AzureRoleDefinition)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/AzureRoleDefinition.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/AzureRoleDefinition.cs deleted file mode 100644 index f770872147..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/AzureRoleDefinition.cs +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Role definition properties. - public partial class AzureRoleDefinition - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal AzureRoleDefinition() - { - Permissions = new ChangeTrackingList(); - Scopes = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The role definition ID. - /// The role definition name. - /// If this is a service role. - /// Role definition permissions. - /// Role definition assignable scopes. - /// Keeps track of any properties unknown to the library. - internal AzureRoleDefinition(string id, string name, bool? isServiceRole, IReadOnlyList permissions, IReadOnlyList scopes, IDictionary serializedAdditionalRawData) - { - Id = id; - Name = name; - IsServiceRole = isServiceRole; - Permissions = permissions; - Scopes = scopes; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The role definition ID. - [WirePath("id")] - public string Id { get; } - /// The role definition name. - [WirePath("name")] - public string Name { get; } - /// If this is a service role. - [WirePath("isServiceRole")] - public bool? IsServiceRole { get; } - /// Role definition permissions. - [WirePath("permissions")] - public IReadOnlyList Permissions { get; } - /// Role definition assignable scopes. - [WirePath("scopes")] - public IReadOnlyList Scopes { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.Serialization.cs deleted file mode 100644 index 5577ee1465..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.Serialization.cs +++ /dev/null @@ -1,293 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class DataManifestCustomResourceFunctionDefinition : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataManifestCustomResourceFunctionDefinition)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(FullyQualifiedResourceType)) - { - writer.WritePropertyName("fullyQualifiedResourceType"u8); - writer.WriteStringValue(FullyQualifiedResourceType.Value); - } - if (Optional.IsCollectionDefined(DefaultProperties)) - { - writer.WritePropertyName("defaultProperties"u8); - writer.WriteStartArray(); - foreach (var item in DefaultProperties) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(AllowCustomProperties)) - { - writer.WritePropertyName("allowCustomProperties"u8); - writer.WriteBooleanValue(AllowCustomProperties.Value); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - DataManifestCustomResourceFunctionDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataManifestCustomResourceFunctionDefinition)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDataManifestCustomResourceFunctionDefinition(document.RootElement, options); - } - - internal static DataManifestCustomResourceFunctionDefinition DeserializeDataManifestCustomResourceFunctionDefinition(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - ResourceType? fullyQualifiedResourceType = default; - IReadOnlyList defaultProperties = default; - bool? allowCustomProperties = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("fullyQualifiedResourceType"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - fullyQualifiedResourceType = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("defaultProperties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - defaultProperties = array; - continue; - } - if (property.NameEquals("allowCustomProperties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - allowCustomProperties = property.Value.GetBoolean(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new DataManifestCustomResourceFunctionDefinition(name, fullyQualifiedResourceType, defaultProperties ?? new ChangeTrackingList(), allowCustomProperties, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(FullyQualifiedResourceType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" fullyQualifiedResourceType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(FullyQualifiedResourceType)) - { - builder.Append(" fullyQualifiedResourceType: "); - builder.AppendLine($"'{FullyQualifiedResourceType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DefaultProperties), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" defaultProperties: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(DefaultProperties)) - { - if (DefaultProperties.Any()) - { - builder.Append(" defaultProperties: "); - builder.AppendLine("["); - foreach (var item in DefaultProperties) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(AllowCustomProperties), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" allowCustomProperties: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(AllowCustomProperties)) - { - builder.Append(" allowCustomProperties: "); - var boolValue = AllowCustomProperties.Value == true ? "true" : "false"; - builder.AppendLine($"{boolValue}"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(DataManifestCustomResourceFunctionDefinition)} does not support writing '{options.Format}' format."); - } - } - - DataManifestCustomResourceFunctionDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeDataManifestCustomResourceFunctionDefinition(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DataManifestCustomResourceFunctionDefinition)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.cs deleted file mode 100644 index 4f66f5b04c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.cs +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The custom resource function definition. - public partial class DataManifestCustomResourceFunctionDefinition - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal DataManifestCustomResourceFunctionDefinition() - { - DefaultProperties = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The function name as it will appear in the policy rule. eg - 'vault'. - /// The fully qualified control plane resource type that this function represents. eg - 'Microsoft.KeyVault/vaults'. - /// The top-level properties that can be selected on the function's output. eg - [ "name", "location" ] if vault().name and vault().location are supported. - /// A value indicating whether the custom properties within the property bag are allowed. Needs api-version to be specified in the policy rule eg - vault('2019-06-01'). - /// Keeps track of any properties unknown to the library. - internal DataManifestCustomResourceFunctionDefinition(string name, ResourceType? fullyQualifiedResourceType, IReadOnlyList defaultProperties, bool? allowCustomProperties, IDictionary serializedAdditionalRawData) - { - Name = name; - FullyQualifiedResourceType = fullyQualifiedResourceType; - DefaultProperties = defaultProperties; - AllowCustomProperties = allowCustomProperties; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The function name as it will appear in the policy rule. eg - 'vault'. - [WirePath("name")] - public string Name { get; } - /// The fully qualified control plane resource type that this function represents. eg - 'Microsoft.KeyVault/vaults'. - [WirePath("fullyQualifiedResourceType")] - public ResourceType? FullyQualifiedResourceType { get; } - /// The top-level properties that can be selected on the function's output. eg - [ "name", "location" ] if vault().name and vault().location are supported. - [WirePath("defaultProperties")] - public IReadOnlyList DefaultProperties { get; } - /// A value indicating whether the custom properties within the property bag are allowed. Needs api-version to be specified in the policy rule eg - vault('2019-06-01'). - [WirePath("allowCustomProperties")] - public bool? AllowCustomProperties { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestEffect.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestEffect.Serialization.cs deleted file mode 100644 index 3556bcce27..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestEffect.Serialization.cs +++ /dev/null @@ -1,207 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class DataPolicyManifestEffect : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataPolicyManifestEffect)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(DetailsSchema)) - { - writer.WritePropertyName("detailsSchema"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(DetailsSchema); -#else - using (JsonDocument document = JsonDocument.Parse(DetailsSchema, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - DataPolicyManifestEffect IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataPolicyManifestEffect)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDataPolicyManifestEffect(document.RootElement, options); - } - - internal static DataPolicyManifestEffect DeserializeDataPolicyManifestEffect(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - BinaryData detailsSchema = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("detailsSchema"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - detailsSchema = BinaryData.FromString(property.Value.GetRawText()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new DataPolicyManifestEffect(name, detailsSchema, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DetailsSchema), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" detailsSchema: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DetailsSchema)) - { - builder.Append(" detailsSchema: "); - builder.AppendLine($"'{DetailsSchema.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(DataPolicyManifestEffect)} does not support writing '{options.Format}' format."); - } - } - - DataPolicyManifestEffect IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeDataPolicyManifestEffect(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DataPolicyManifestEffect)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestEffect.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestEffect.cs deleted file mode 100644 index 140fcae664..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestEffect.cs +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The data effect definition. - public partial class DataPolicyManifestEffect - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal DataPolicyManifestEffect() - { - } - - /// Initializes a new instance of . - /// The data effect name. - /// The data effect details schema. - /// Keeps track of any properties unknown to the library. - internal DataPolicyManifestEffect(string name, BinaryData detailsSchema, IDictionary serializedAdditionalRawData) - { - Name = name; - DetailsSchema = detailsSchema; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The data effect name. - [WirePath("name")] - public string Name { get; } - /// - /// The data effect details schema. - /// - /// To assign an object to this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("detailsSchema")] - public BinaryData DetailsSchema { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestListResult.Serialization.cs deleted file mode 100644 index 8e5ca3b53f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class DataPolicyManifestListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataPolicyManifestListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - DataPolicyManifestListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataPolicyManifestListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDataPolicyManifestListResult(document.RootElement, options); - } - - internal static DataPolicyManifestListResult DeserializeDataPolicyManifestListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(DataPolicyManifestData.DeserializeDataPolicyManifestData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new DataPolicyManifestListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(DataPolicyManifestListResult)} does not support writing '{options.Format}' format."); - } - } - - DataPolicyManifestListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeDataPolicyManifestListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DataPolicyManifestListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestListResult.cs deleted file mode 100644 index 769a87638b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of data policy manifests. - internal partial class DataPolicyManifestListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal DataPolicyManifestListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of data policy manifests. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal DataPolicyManifestListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of data policy manifests. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/EnforcementMode.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/EnforcementMode.cs deleted file mode 100644 index 239bc9da67..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/EnforcementMode.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The policy assignment enforcement mode. Possible values are Default and DoNotEnforce. - public readonly partial struct EnforcementMode : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public EnforcementMode(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string DefaultValue = "Default"; - private const string DoNotEnforceValue = "DoNotEnforce"; - - /// The policy effect is enforced during resource creation or update. - public static EnforcementMode Default { get; } = new EnforcementMode(DefaultValue); - /// The policy effect is not enforced during resource creation or update. - public static EnforcementMode DoNotEnforce { get; } = new EnforcementMode(DoNotEnforceValue); - /// Determines if two values are the same. - public static bool operator ==(EnforcementMode left, EnforcementMode right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(EnforcementMode left, EnforcementMode right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator EnforcementMode(string value) => new EnforcementMode(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is EnforcementMode other && Equals(other); - /// - public bool Equals(EnforcementMode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExportTemplate.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExportTemplate.Serialization.cs deleted file mode 100644 index 8d4f146fb5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExportTemplate.Serialization.cs +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ExportTemplate : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ExportTemplate)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Resources)) - { - writer.WritePropertyName("resources"u8); - writer.WriteStartArray(); - foreach (var item in Resources) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(Options)) - { - writer.WritePropertyName("options"u8); - writer.WriteStringValue(Options); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ExportTemplate IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ExportTemplate)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeExportTemplate(document.RootElement, options); - } - - internal static ExportTemplate DeserializeExportTemplate(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IList resources = default; - string options0 = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("resources"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - resources = array; - continue; - } - if (property.NameEquals("options"u8)) - { - options0 = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ExportTemplate(resources ?? new ChangeTrackingList(), options0, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ExportTemplate)} does not support writing '{options.Format}' format."); - } - } - - ExportTemplate IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeExportTemplate(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ExportTemplate)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExportTemplate.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExportTemplate.cs deleted file mode 100644 index 43ce04a802..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExportTemplate.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Export resource group template request parameters. - public partial class ExportTemplate - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ExportTemplate() - { - Resources = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The IDs of the resources to filter the export by. To export all resources, supply an array with single entry '*'. - /// The export template options. A CSV-formatted list containing zero or more of the following: 'IncludeParameterDefaultValue', 'IncludeComments', 'SkipResourceNameParameterization', 'SkipAllParameterization'. - /// Keeps track of any properties unknown to the library. - internal ExportTemplate(IList resources, string options, IDictionary serializedAdditionalRawData) - { - Resources = resources; - Options = options; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The IDs of the resources to filter the export by. To export all resources, supply an array with single entry '*'. - [WirePath("resources")] - public IList Resources { get; } - /// The export template options. A CSV-formatted list containing zero or more of the following: 'IncludeParameterDefaultValue', 'IncludeComments', 'SkipResourceNameParameterization', 'SkipAllParameterization'. - [WirePath("options")] - public string Options { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocation.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocation.Serialization.cs deleted file mode 100644 index d3763ccf2d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocation.Serialization.cs +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - [JsonConverter(typeof(ExtendedLocationConverter))] - public partial class ExtendedLocation : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ExtendedLocation)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(ExtendedLocationType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ExtendedLocationType.Value.ToString()); - } - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - } - - ExtendedLocation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ExtendedLocation)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeExtendedLocation(document.RootElement, options); - } - - internal static ExtendedLocation DeserializeExtendedLocation(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ExtendedLocationType? type = default; - string name = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = new ExtendedLocationType(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - } - return new ExtendedLocation(type, name); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ExtendedLocationType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" type: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ExtendedLocationType)) - { - builder.Append(" type: "); - builder.AppendLine($"'{ExtendedLocationType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ExtendedLocation)} does not support writing '{options.Format}' format."); - } - } - - ExtendedLocation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeExtendedLocation(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ExtendedLocation)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - internal partial class ExtendedLocationConverter : JsonConverter - { - public override void Write(Utf8JsonWriter writer, ExtendedLocation model, JsonSerializerOptions options) - { - writer.WriteObjectValue(model, ModelSerializationExtensions.WireOptions); - } - - public override ExtendedLocation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - return DeserializeExtendedLocation(document.RootElement); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocation.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocation.cs deleted file mode 100644 index c052d4f1e8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocation.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Resource extended location. - [PropertyReferenceType] - public partial class ExtendedLocation - { - /// Initializes a new instance of . - [InitializationConstructor] - public ExtendedLocation() - { - } - - /// Initializes a new instance of . - /// The extended location type. - /// The extended location name. - [SerializationConstructor] - internal ExtendedLocation(ExtendedLocationType? extendedLocationType, string name) - { - ExtendedLocationType = extendedLocationType; - Name = name; - } - - /// The extended location type. - [WirePath("type")] - public ExtendedLocationType? ExtendedLocationType { get; set; } - /// The extended location name. - [WirePath("name")] - public string Name { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocationType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocationType.cs deleted file mode 100644 index 76cfe6ccdb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocationType.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The extended location type. - public readonly partial struct ExtendedLocationType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ExtendedLocationType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string EdgeZoneValue = "EdgeZone"; - - /// EdgeZone. - public static ExtendedLocationType EdgeZone { get; } = new ExtendedLocationType(EdgeZoneValue); - /// Determines if two values are the same. - public static bool operator ==(ExtendedLocationType left, ExtendedLocationType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ExtendedLocationType left, ExtendedLocationType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ExtendedLocationType(string value) => new ExtendedLocationType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ExtendedLocationType other && Equals(other); - /// - public bool Equals(ExtendedLocationType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/FeatureOperationsListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/FeatureOperationsListResult.Serialization.cs deleted file mode 100644 index d1afa4568e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/FeatureOperationsListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class FeatureOperationsListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(FeatureOperationsListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - FeatureOperationsListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(FeatureOperationsListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeFeatureOperationsListResult(document.RootElement, options); - } - - internal static FeatureOperationsListResult DeserializeFeatureOperationsListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(FeatureData.DeserializeFeatureData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new FeatureOperationsListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(FeatureOperationsListResult)} does not support writing '{options.Format}' format."); - } - } - - FeatureOperationsListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeFeatureOperationsListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(FeatureOperationsListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/FeatureOperationsListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/FeatureOperationsListResult.cs deleted file mode 100644 index e2063f4235..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/FeatureOperationsListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of previewed features. - internal partial class FeatureOperationsListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal FeatureOperationsListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The array of features. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal FeatureOperationsListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The array of features. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/FeatureProperties.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/FeatureProperties.Serialization.cs deleted file mode 100644 index b9de6a882e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/FeatureProperties.Serialization.cs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class FeatureProperties : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(FeatureProperties)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(State)) - { - writer.WritePropertyName("state"u8); - writer.WriteStringValue(State); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - FeatureProperties IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(FeatureProperties)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeFeatureProperties(document.RootElement, options); - } - - internal static FeatureProperties DeserializeFeatureProperties(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string state = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("state"u8)) - { - state = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new FeatureProperties(state, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(State), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" state: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(State)) - { - builder.Append(" state: "); - if (State.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{State}'''"); - } - else - { - builder.AppendLine($"'{State}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(FeatureProperties)} does not support writing '{options.Format}' format."); - } - } - - FeatureProperties IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeFeatureProperties(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(FeatureProperties)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/FeatureProperties.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/FeatureProperties.cs deleted file mode 100644 index bab8758f08..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/FeatureProperties.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Information about feature. - internal partial class FeatureProperties - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal FeatureProperties() - { - } - - /// Initializes a new instance of . - /// The registration state of the feature for the subscription. - /// Keeps track of any properties unknown to the library. - internal FeatureProperties(string state, IDictionary serializedAdditionalRawData) - { - State = state; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The registration state of the feature for the subscription. - [WirePath("state")] - public string State { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationExpanded.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationExpanded.Serialization.cs deleted file mode 100644 index 0ea0b73f73..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationExpanded.Serialization.cs +++ /dev/null @@ -1,409 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class LocationExpanded : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(LocationExpanded)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && Optional.IsDefined(SubscriptionId)) - { - writer.WritePropertyName("subscriptionId"u8); - writer.WriteStringValue(SubscriptionId); - } - if (options.Format != "W" && Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (options.Format != "W" && Optional.IsDefined(LocationType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(LocationType.Value.ToSerialString()); - } - if (options.Format != "W" && Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (options.Format != "W" && Optional.IsDefined(RegionalDisplayName)) - { - writer.WritePropertyName("regionalDisplayName"u8); - writer.WriteStringValue(RegionalDisplayName); - } - if (Optional.IsDefined(Metadata)) - { - writer.WritePropertyName("metadata"u8); - writer.WriteObjectValue(Metadata, options); - } - if (Optional.IsCollectionDefined(AvailabilityZoneMappings)) - { - writer.WritePropertyName("availabilityZoneMappings"u8); - writer.WriteStartArray(); - foreach (var item in AvailabilityZoneMappings) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - LocationExpanded IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(LocationExpanded)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeLocationExpanded(document.RootElement, options); - } - - internal static LocationExpanded DeserializeLocationExpanded(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string id = default; - string subscriptionId = default; - string name = default; - LocationType? type = default; - string displayName = default; - string regionalDisplayName = default; - LocationMetadata metadata = default; - IReadOnlyList availabilityZoneMappings = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("subscriptionId"u8)) - { - subscriptionId = property.Value.GetString(); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = property.Value.GetString().ToLocationType(); - continue; - } - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (property.NameEquals("regionalDisplayName"u8)) - { - regionalDisplayName = property.Value.GetString(); - continue; - } - if (property.NameEquals("metadata"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - metadata = LocationMetadata.DeserializeLocationMetadata(property.Value, options); - continue; - } - if (property.NameEquals("availabilityZoneMappings"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(Models.AvailabilityZoneMappings.DeserializeAvailabilityZoneMappings(item, options)); - } - availabilityZoneMappings = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new LocationExpanded( - id, - subscriptionId, - name, - type, - displayName, - regionalDisplayName, - metadata, - availabilityZoneMappings ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - if (Id.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Id}'''"); - } - else - { - builder.AppendLine($"'{Id}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SubscriptionId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" subscriptionId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SubscriptionId)) - { - builder.Append(" subscriptionId: "); - if (SubscriptionId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{SubscriptionId}'''"); - } - else - { - builder.AppendLine($"'{SubscriptionId}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(RegionalDisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" regionalDisplayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(RegionalDisplayName)) - { - builder.Append(" regionalDisplayName: "); - if (RegionalDisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{RegionalDisplayName}'''"); - } - else - { - builder.AppendLine($"'{RegionalDisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Metadata), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" metadata: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Metadata)) - { - builder.Append(" metadata: "); - BicepSerializationHelpers.AppendChildObject(builder, Metadata, options, 2, false, " metadata: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(AvailabilityZoneMappings), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" availabilityZoneMappings: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(AvailabilityZoneMappings)) - { - if (AvailabilityZoneMappings.Any()) - { - builder.Append(" availabilityZoneMappings: "); - builder.AppendLine("["); - foreach (var item in AvailabilityZoneMappings) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " availabilityZoneMappings: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(LocationExpanded)} does not support writing '{options.Format}' format."); - } - } - - LocationExpanded IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLocationExpanded(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(LocationExpanded)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationExpanded.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationExpanded.cs deleted file mode 100644 index 60e4a76f90..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationExpanded.cs +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Location information. - public partial class LocationExpanded - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal LocationExpanded() - { - AvailabilityZoneMappings = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The fully qualified ID of the location. For example, /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74/locations/westus. - /// The subscription ID. - /// The location name. - /// The location type. - /// The display name of the location. - /// The display name of the location and its region. - /// Metadata of the location, such as lat/long, paired region, and others. - /// The availability zone mappings for this region. - /// Keeps track of any properties unknown to the library. - internal LocationExpanded(string id, string subscriptionId, string name, LocationType? locationType, string displayName, string regionalDisplayName, LocationMetadata metadata, IReadOnlyList availabilityZoneMappings, IDictionary serializedAdditionalRawData) - { - Id = id; - SubscriptionId = subscriptionId; - Name = name; - LocationType = locationType; - DisplayName = displayName; - RegionalDisplayName = regionalDisplayName; - Metadata = metadata; - AvailabilityZoneMappings = availabilityZoneMappings; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The fully qualified ID of the location. For example, /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74/locations/westus. - [WirePath("id")] - public string Id { get; } - /// The subscription ID. - [WirePath("subscriptionId")] - public string SubscriptionId { get; } - /// The location name. - [WirePath("name")] - public string Name { get; } - /// The location type. - [WirePath("type")] - public LocationType? LocationType { get; } - /// The display name of the location. - [WirePath("displayName")] - public string DisplayName { get; } - /// The display name of the location and its region. - [WirePath("regionalDisplayName")] - public string RegionalDisplayName { get; } - /// Metadata of the location, such as lat/long, paired region, and others. - [WirePath("metadata")] - public LocationMetadata Metadata { get; } - /// The availability zone mappings for this region. - [WirePath("availabilityZoneMappings")] - public IReadOnlyList AvailabilityZoneMappings { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationListResult.Serialization.cs deleted file mode 100644 index d497dbadaf..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationListResult.Serialization.cs +++ /dev/null @@ -1,185 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class LocationListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(LocationListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - LocationListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(LocationListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeLocationListResult(document.RootElement, options); - } - - internal static LocationListResult DeserializeLocationListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(LocationExpanded.DeserializeLocationExpanded(item, options)); - } - value = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new LocationListResult(value ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(LocationListResult)} does not support writing '{options.Format}' format."); - } - } - - LocationListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLocationListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(LocationListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationListResult.cs deleted file mode 100644 index a614638e72..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationListResult.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Location list operation response. - internal partial class LocationListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal LocationListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of locations. - /// Keeps track of any properties unknown to the library. - internal LocationListResult(IReadOnlyList value, IDictionary serializedAdditionalRawData) - { - Value = value; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of locations. - public IReadOnlyList Value { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationMetadata.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationMetadata.Serialization.cs deleted file mode 100644 index 7f29d1a639..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationMetadata.Serialization.cs +++ /dev/null @@ -1,443 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class LocationMetadata : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(LocationMetadata)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(RegionType)) - { - writer.WritePropertyName("regionType"u8); - writer.WriteStringValue(RegionType.Value.ToString()); - } - if (options.Format != "W" && Optional.IsDefined(RegionCategory)) - { - writer.WritePropertyName("regionCategory"u8); - writer.WriteStringValue(RegionCategory.Value.ToString()); - } - if (options.Format != "W" && Optional.IsDefined(Geography)) - { - writer.WritePropertyName("geography"u8); - writer.WriteStringValue(Geography); - } - if (options.Format != "W" && Optional.IsDefined(GeographyGroup)) - { - writer.WritePropertyName("geographyGroup"u8); - writer.WriteStringValue(GeographyGroup); - } - if (options.Format != "W" && Optional.IsDefined(Longitude)) - { - writer.WritePropertyName("longitude"u8); - WriteLongitude(writer, options); - } - if (options.Format != "W" && Optional.IsDefined(Latitude)) - { - writer.WritePropertyName("latitude"u8); - WriteLatitude(writer, options); - } - if (options.Format != "W" && Optional.IsDefined(PhysicalLocation)) - { - writer.WritePropertyName("physicalLocation"u8); - writer.WriteStringValue(PhysicalLocation); - } - if (Optional.IsCollectionDefined(PairedRegions)) - { - writer.WritePropertyName("pairedRegion"u8); - writer.WriteStartArray(); - foreach (var item in PairedRegions) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(HomeLocation)) - { - writer.WritePropertyName("homeLocation"u8); - writer.WriteStringValue(HomeLocation); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - LocationMetadata IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(LocationMetadata)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeLocationMetadata(document.RootElement, options); - } - - internal static LocationMetadata DeserializeLocationMetadata(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - RegionType? regionType = default; - RegionCategory? regionCategory = default; - string geography = default; - string geographyGroup = default; - double? longitude = default; - double? latitude = default; - string physicalLocation = default; - IReadOnlyList pairedRegion = default; - string homeLocation = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("regionType"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - regionType = new RegionType(property.Value.GetString()); - continue; - } - if (property.NameEquals("regionCategory"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - regionCategory = new RegionCategory(property.Value.GetString()); - continue; - } - if (property.NameEquals("geography"u8)) - { - geography = property.Value.GetString(); - continue; - } - if (property.NameEquals("geographyGroup"u8)) - { - geographyGroup = property.Value.GetString(); - continue; - } - if (property.NameEquals("longitude"u8)) - { - ReadLongitude(property, ref longitude); - continue; - } - if (property.NameEquals("latitude"u8)) - { - ReadLatitude(property, ref latitude); - continue; - } - if (property.NameEquals("physicalLocation"u8)) - { - physicalLocation = property.Value.GetString(); - continue; - } - if (property.NameEquals("pairedRegion"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(PairedRegion.DeserializePairedRegion(item, options)); - } - pairedRegion = array; - continue; - } - if (property.NameEquals("homeLocation"u8)) - { - homeLocation = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new LocationMetadata( - regionType, - regionCategory, - geography, - geographyGroup, - longitude, - latitude, - physicalLocation, - pairedRegion ?? new ChangeTrackingList(), - homeLocation, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(RegionType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" regionType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(RegionType)) - { - builder.Append(" regionType: "); - builder.AppendLine($"'{RegionType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(RegionCategory), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" regionCategory: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(RegionCategory)) - { - builder.Append(" regionCategory: "); - builder.AppendLine($"'{RegionCategory.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Geography), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" geography: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Geography)) - { - builder.Append(" geography: "); - if (Geography.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Geography}'''"); - } - else - { - builder.AppendLine($"'{Geography}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(GeographyGroup), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" geographyGroup: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(GeographyGroup)) - { - builder.Append(" geographyGroup: "); - if (GeographyGroup.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{GeographyGroup}'''"); - } - else - { - builder.AppendLine($"'{GeographyGroup}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Longitude), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" longitude: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Longitude)) - { - builder.Append(" longitude: "); - builder.AppendLine($"'{Longitude.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Latitude), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" latitude: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Latitude)) - { - builder.Append(" latitude: "); - builder.AppendLine($"'{Latitude.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PhysicalLocation), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" physicalLocation: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PhysicalLocation)) - { - builder.Append(" physicalLocation: "); - if (PhysicalLocation.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{PhysicalLocation}'''"); - } - else - { - builder.AppendLine($"'{PhysicalLocation}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PairedRegions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" pairedRegion: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(PairedRegions)) - { - if (PairedRegions.Any()) - { - builder.Append(" pairedRegion: "); - builder.AppendLine("["); - foreach (var item in PairedRegions) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " pairedRegion: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(HomeLocation), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" homeLocation: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(HomeLocation)) - { - builder.Append(" homeLocation: "); - if (HomeLocation.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{HomeLocation}'''"); - } - else - { - builder.AppendLine($"'{HomeLocation}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(LocationMetadata)} does not support writing '{options.Format}' format."); - } - } - - LocationMetadata IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLocationMetadata(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(LocationMetadata)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationMetadata.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationMetadata.cs deleted file mode 100644 index 4fe985db7d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationMetadata.cs +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Location metadata information. - public partial class LocationMetadata - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal LocationMetadata() - { - PairedRegions = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The type of the region. - /// The category of the region. - /// The geography of the location. - /// The geography group of the location. - /// The longitude of the location. - /// The latitude of the location. - /// The physical location of the Azure location. - /// The regions paired to this region. - /// The home location of an edge zone. - /// Keeps track of any properties unknown to the library. - internal LocationMetadata(RegionType? regionType, RegionCategory? regionCategory, string geography, string geographyGroup, double? longitude, double? latitude, string physicalLocation, IReadOnlyList pairedRegions, string homeLocation, IDictionary serializedAdditionalRawData) - { - RegionType = regionType; - RegionCategory = regionCategory; - Geography = geography; - GeographyGroup = geographyGroup; - Longitude = longitude; - Latitude = latitude; - PhysicalLocation = physicalLocation; - PairedRegions = pairedRegions; - HomeLocation = homeLocation; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The type of the region. - [WirePath("regionType")] - public RegionType? RegionType { get; } - /// The category of the region. - [WirePath("regionCategory")] - public RegionCategory? RegionCategory { get; } - /// The geography of the location. - [WirePath("geography")] - public string Geography { get; } - /// The geography group of the location. - [WirePath("geographyGroup")] - public string GeographyGroup { get; } - /// The physical location of the Azure location. - [WirePath("physicalLocation")] - public string PhysicalLocation { get; } - /// The regions paired to this region. - [WirePath("pairedRegion")] - public IReadOnlyList PairedRegions { get; } - /// The home location of an edge zone. - [WirePath("homeLocation")] - public string HomeLocation { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationType.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationType.Serialization.cs deleted file mode 100644 index 95769ed54d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationType.Serialization.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.Resources.Models -{ - internal static partial class LocationTypeExtensions - { - public static string ToSerialString(this LocationType value) => value switch - { - LocationType.Region => "Region", - LocationType.EdgeZone => "EdgeZone", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown LocationType value.") - }; - - public static LocationType ToLocationType(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Region")) return LocationType.Region; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "EdgeZone")) return LocationType.EdgeZone; - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown LocationType value."); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationType.cs deleted file mode 100644 index fe985afe37..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/LocationType.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.Resources.Models -{ - /// The location type. - public enum LocationType - { - /// Region. - Region, - /// EdgeZone. - EdgeZone - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagedByTenant.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagedByTenant.Serialization.cs deleted file mode 100644 index e9c97cb3ba..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagedByTenant.Serialization.cs +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ManagedByTenant : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagedByTenant)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(TenantId)) - { - writer.WritePropertyName("tenantId"u8); - writer.WriteStringValue(TenantId.Value); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ManagedByTenant IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagedByTenant)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagedByTenant(document.RootElement, options); - } - - internal static ManagedByTenant DeserializeManagedByTenant(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - Guid? tenantId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("tenantId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - tenantId = property.Value.GetGuid(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagedByTenant(tenantId, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TenantId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenantId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TenantId)) - { - builder.Append(" tenantId: "); - builder.AppendLine($"'{TenantId.Value.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagedByTenant)} does not support writing '{options.Format}' format."); - } - } - - ManagedByTenant IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagedByTenant(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagedByTenant)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagedByTenant.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagedByTenant.cs deleted file mode 100644 index 17afaec3ad..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagedByTenant.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Information about a tenant managing the subscription. - public partial class ManagedByTenant - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagedByTenant() - { - } - - /// Initializes a new instance of . - /// The tenant ID of the managing tenant. This is a GUID. - /// Keeps track of any properties unknown to the library. - internal ManagedByTenant(Guid? tenantId, IDictionary serializedAdditionalRawData) - { - TenantId = tenantId; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The tenant ID of the managing tenant. This is a GUID. - [WirePath("tenantId")] - public Guid? TenantId { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockLevel.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockLevel.cs deleted file mode 100644 index f3f6fa4cf8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockLevel.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The level of the lock. Possible values are: NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users are able to read and modify the resources, but not delete. ReadOnly means authorized users can only read from a resource, but they can't modify or delete it. - public readonly partial struct ManagementLockLevel : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ManagementLockLevel(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string NotSpecifiedValue = "NotSpecified"; - private const string CanNotDeleteValue = "CanNotDelete"; - private const string ReadOnlyValue = "ReadOnly"; - - /// NotSpecified. - public static ManagementLockLevel NotSpecified { get; } = new ManagementLockLevel(NotSpecifiedValue); - /// CanNotDelete. - public static ManagementLockLevel CanNotDelete { get; } = new ManagementLockLevel(CanNotDeleteValue); - /// ReadOnly. - public static ManagementLockLevel ReadOnly { get; } = new ManagementLockLevel(ReadOnlyValue); - /// Determines if two values are the same. - public static bool operator ==(ManagementLockLevel left, ManagementLockLevel right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ManagementLockLevel left, ManagementLockLevel right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ManagementLockLevel(string value) => new ManagementLockLevel(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ManagementLockLevel other && Equals(other); - /// - public bool Equals(ManagementLockLevel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockListResult.Serialization.cs deleted file mode 100644 index 5d7754328f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class ManagementLockListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementLockListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ManagementLockListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementLockListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementLockListResult(document.RootElement, options); - } - - internal static ManagementLockListResult DeserializeManagementLockListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ManagementLockData.DeserializeManagementLockData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementLockListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementLockListResult)} does not support writing '{options.Format}' format."); - } - } - - ManagementLockListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementLockListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementLockListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockListResult.cs deleted file mode 100644 index 7702747e45..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The list of locks. - internal partial class ManagementLockListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ManagementLockListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The list of locks. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal ManagementLockListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The list of locks. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockOwner.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockOwner.Serialization.cs deleted file mode 100644 index 36a902f6d0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockOwner.Serialization.cs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ManagementLockOwner : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementLockOwner)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(ApplicationId)) - { - writer.WritePropertyName("applicationId"u8); - writer.WriteStringValue(ApplicationId); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ManagementLockOwner IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ManagementLockOwner)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeManagementLockOwner(document.RootElement, options); - } - - internal static ManagementLockOwner DeserializeManagementLockOwner(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string applicationId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("applicationId"u8)) - { - applicationId = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ManagementLockOwner(applicationId, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ApplicationId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" applicationId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ApplicationId)) - { - builder.Append(" applicationId: "); - if (ApplicationId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ApplicationId}'''"); - } - else - { - builder.AppendLine($"'{ApplicationId}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ManagementLockOwner)} does not support writing '{options.Format}' format."); - } - } - - ManagementLockOwner IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeManagementLockOwner(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ManagementLockOwner)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockOwner.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockOwner.cs deleted file mode 100644 index 7cb1045193..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockOwner.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Lock owner properties. - public partial class ManagementLockOwner - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ManagementLockOwner() - { - } - - /// Initializes a new instance of . - /// The application ID of the lock owner. - /// Keeps track of any properties unknown to the library. - internal ManagementLockOwner(string applicationId, IDictionary serializedAdditionalRawData) - { - ApplicationId = applicationId; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The application ID of the lock owner. - [WirePath("applicationId")] - public string ApplicationId { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/NonComplianceMessage.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/NonComplianceMessage.Serialization.cs deleted file mode 100644 index 70428e4798..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/NonComplianceMessage.Serialization.cs +++ /dev/null @@ -1,201 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class NonComplianceMessage : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(NonComplianceMessage)} does not support writing '{format}' format."); - } - - writer.WritePropertyName("message"u8); - writer.WriteStringValue(Message); - if (Optional.IsDefined(PolicyDefinitionReferenceId)) - { - writer.WritePropertyName("policyDefinitionReferenceId"u8); - writer.WriteStringValue(PolicyDefinitionReferenceId); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - NonComplianceMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(NonComplianceMessage)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeNonComplianceMessage(document.RootElement, options); - } - - internal static NonComplianceMessage DeserializeNonComplianceMessage(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string message = default; - string policyDefinitionReferenceId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("message"u8)) - { - message = property.Value.GetString(); - continue; - } - if (property.NameEquals("policyDefinitionReferenceId"u8)) - { - policyDefinitionReferenceId = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new NonComplianceMessage(message, policyDefinitionReferenceId, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Message), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" message: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Message)) - { - builder.Append(" message: "); - if (Message.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Message}'''"); - } - else - { - builder.AppendLine($"'{Message}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyDefinitionReferenceId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyDefinitionReferenceId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PolicyDefinitionReferenceId)) - { - builder.Append(" policyDefinitionReferenceId: "); - if (PolicyDefinitionReferenceId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{PolicyDefinitionReferenceId}'''"); - } - else - { - builder.AppendLine($"'{PolicyDefinitionReferenceId}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(NonComplianceMessage)} does not support writing '{options.Format}' format."); - } - } - - NonComplianceMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeNonComplianceMessage(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(NonComplianceMessage)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/NonComplianceMessage.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/NonComplianceMessage.cs deleted file mode 100644 index a412852eaa..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/NonComplianceMessage.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// A message that describes why a resource is non-compliant with the policy. This is shown in 'deny' error messages and on resource's non-compliant compliance results. - public partial class NonComplianceMessage - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// A message that describes why a resource is non-compliant with the policy. This is shown in 'deny' error messages and on resource's non-compliant compliance results. - /// is null. - public NonComplianceMessage(string message) - { - Argument.AssertNotNull(message, nameof(message)); - - Message = message; - } - - /// Initializes a new instance of . - /// A message that describes why a resource is non-compliant with the policy. This is shown in 'deny' error messages and on resource's non-compliant compliance results. - /// The policy definition reference ID within a policy set definition the message is intended for. This is only applicable if the policy assignment assigns a policy set definition. If this is not provided the message applies to all policies assigned by this policy assignment. - /// Keeps track of any properties unknown to the library. - internal NonComplianceMessage(string message, string policyDefinitionReferenceId, IDictionary serializedAdditionalRawData) - { - Message = message; - PolicyDefinitionReferenceId = policyDefinitionReferenceId; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal NonComplianceMessage() - { - } - - /// A message that describes why a resource is non-compliant with the policy. This is shown in 'deny' error messages and on resource's non-compliant compliance results. - [WirePath("message")] - public string Message { get; set; } - /// The policy definition reference ID within a policy set definition the message is intended for. This is only applicable if the policy assignment assigns a policy set definition. If this is not provided the message applies to all policies assigned by this policy assignment. - [WirePath("policyDefinitionReferenceId")] - public string PolicyDefinitionReferenceId { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PairedRegion.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PairedRegion.Serialization.cs deleted file mode 100644 index 8625021fca..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PairedRegion.Serialization.cs +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class PairedRegion : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PairedRegion)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && Optional.IsDefined(SubscriptionId)) - { - writer.WritePropertyName("subscriptionId"u8); - writer.WriteStringValue(SubscriptionId); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - PairedRegion IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PairedRegion)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePairedRegion(document.RootElement, options); - } - - internal static PairedRegion DeserializePairedRegion(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - string id = default; - string subscriptionId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("subscriptionId"u8)) - { - subscriptionId = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PairedRegion(name, id, subscriptionId, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - if (Id.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Id}'''"); - } - else - { - builder.AppendLine($"'{Id}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SubscriptionId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" subscriptionId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SubscriptionId)) - { - builder.Append(" subscriptionId: "); - if (SubscriptionId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{SubscriptionId}'''"); - } - else - { - builder.AppendLine($"'{SubscriptionId}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PairedRegion)} does not support writing '{options.Format}' format."); - } - } - - PairedRegion IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePairedRegion(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PairedRegion)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PairedRegion.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PairedRegion.cs deleted file mode 100644 index b4e30a1a8f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PairedRegion.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Information regarding paired region. - public partial class PairedRegion - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal PairedRegion() - { - } - - /// Initializes a new instance of . - /// The name of the paired region. - /// The fully qualified ID of the location. For example, /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74/locations/westus. - /// The subscription ID. - /// Keeps track of any properties unknown to the library. - internal PairedRegion(string name, string id, string subscriptionId, IDictionary serializedAdditionalRawData) - { - Name = name; - Id = id; - SubscriptionId = subscriptionId; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The name of the paired region. - [WirePath("name")] - public string Name { get; } - /// The fully qualified ID of the location. For example, /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74/locations/westus. - [WirePath("id")] - public string Id { get; } - /// The subscription ID. - [WirePath("subscriptionId")] - public string SubscriptionId { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ParameterDefinitionsValueMetadata.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ParameterDefinitionsValueMetadata.Serialization.cs deleted file mode 100644 index d8c4cc28c1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ParameterDefinitionsValueMetadata.Serialization.cs +++ /dev/null @@ -1,263 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ParameterDefinitionsValueMetadata : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ParameterDefinitionsValueMetadata)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (Optional.IsDefined(Description)) - { - writer.WritePropertyName("description"u8); - writer.WriteStringValue(Description); - } - if (Optional.IsDefined(StrongType)) - { - writer.WritePropertyName("strongType"u8); - writer.WriteStringValue(StrongType); - } - if (Optional.IsDefined(AssignPermissions)) - { - writer.WritePropertyName("assignPermissions"u8); - writer.WriteBooleanValue(AssignPermissions.Value); - } - foreach (var item in AdditionalProperties) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - - ParameterDefinitionsValueMetadata IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ParameterDefinitionsValueMetadata)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeParameterDefinitionsValueMetadata(document.RootElement, options); - } - - internal static ParameterDefinitionsValueMetadata DeserializeParameterDefinitionsValueMetadata(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string displayName = default; - string description = default; - string strongType = default; - bool? assignPermissions = default; - IDictionary additionalProperties = default; - Dictionary additionalPropertiesDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (property.NameEquals("description"u8)) - { - description = property.Value.GetString(); - continue; - } - if (property.NameEquals("strongType"u8)) - { - strongType = property.Value.GetString(); - continue; - } - if (property.NameEquals("assignPermissions"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - assignPermissions = property.Value.GetBoolean(); - continue; - } - additionalPropertiesDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - additionalProperties = additionalPropertiesDictionary; - return new ParameterDefinitionsValueMetadata(displayName, description, strongType, assignPermissions, additionalProperties); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Description), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" description: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Description)) - { - builder.Append(" description: "); - if (Description.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Description}'''"); - } - else - { - builder.AppendLine($"'{Description}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(StrongType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" strongType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(StrongType)) - { - builder.Append(" strongType: "); - if (StrongType.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{StrongType}'''"); - } - else - { - builder.AppendLine($"'{StrongType}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(AssignPermissions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" assignPermissions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(AssignPermissions)) - { - builder.Append(" assignPermissions: "); - var boolValue = AssignPermissions.Value == true ? "true" : "false"; - builder.AppendLine($"{boolValue}"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ParameterDefinitionsValueMetadata)} does not support writing '{options.Format}' format."); - } - } - - ParameterDefinitionsValueMetadata IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeParameterDefinitionsValueMetadata(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ParameterDefinitionsValueMetadata)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ParameterDefinitionsValueMetadata.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ParameterDefinitionsValueMetadata.cs deleted file mode 100644 index 96ed7496b1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ParameterDefinitionsValueMetadata.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// General metadata for the parameter. - public partial class ParameterDefinitionsValueMetadata - { - /// Initializes a new instance of . - public ParameterDefinitionsValueMetadata() - { - AdditionalProperties = new ChangeTrackingDictionary(); - } - - /// Initializes a new instance of . - /// The display name for the parameter. - /// The description of the parameter. - /// Used when assigning the policy definition through the portal. Provides a context aware list of values for the user to choose from. - /// Set to true to have Azure portal create role assignments on the resource ID or resource scope value of this parameter during policy assignment. This property is useful in case you wish to assign permissions outside the assignment scope. - /// Additional Properties. - internal ParameterDefinitionsValueMetadata(string displayName, string description, string strongType, bool? assignPermissions, IDictionary additionalProperties) - { - DisplayName = displayName; - Description = description; - StrongType = strongType; - AssignPermissions = assignPermissions; - AdditionalProperties = additionalProperties; - } - - /// The display name for the parameter. - [WirePath("displayName")] - public string DisplayName { get; set; } - /// The description of the parameter. - [WirePath("description")] - public string Description { get; set; } - /// Used when assigning the policy definition through the portal. Provides a context aware list of values for the user to choose from. - [WirePath("strongType")] - public string StrongType { get; set; } - /// Set to true to have Azure portal create role assignments on the resource ID or resource scope value of this parameter during policy assignment. This property is useful in case you wish to assign permissions outside the assignment scope. - [WirePath("assignPermissions")] - public bool? AssignPermissions { get; set; } - /// - /// Additional Properties - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("AdditionalProperties")] - public IDictionary AdditionalProperties { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/Permission.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/Permission.Serialization.cs deleted file mode 100644 index 6c03d93972..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/Permission.Serialization.cs +++ /dev/null @@ -1,381 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class Permission : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(Permission)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(AllowedActions)) - { - writer.WritePropertyName("actions"u8); - writer.WriteStartArray(); - foreach (var item in AllowedActions) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(DeniedActions)) - { - writer.WritePropertyName("notActions"u8); - writer.WriteStartArray(); - foreach (var item in DeniedActions) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(AllowedDataActions)) - { - writer.WritePropertyName("dataActions"u8); - writer.WriteStartArray(); - foreach (var item in AllowedDataActions) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(DeniedDataActions)) - { - writer.WritePropertyName("notDataActions"u8); - writer.WriteStartArray(); - foreach (var item in DeniedDataActions) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - Permission IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(Permission)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePermission(document.RootElement, options); - } - - internal static Permission DeserializePermission(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList actions = default; - IReadOnlyList notActions = default; - IReadOnlyList dataActions = default; - IReadOnlyList notDataActions = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("actions"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - actions = array; - continue; - } - if (property.NameEquals("notActions"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - notActions = array; - continue; - } - if (property.NameEquals("dataActions"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - dataActions = array; - continue; - } - if (property.NameEquals("notDataActions"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - notDataActions = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new Permission(actions ?? new ChangeTrackingList(), notActions ?? new ChangeTrackingList(), dataActions ?? new ChangeTrackingList(), notDataActions ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(AllowedActions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" actions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(AllowedActions)) - { - if (AllowedActions.Any()) - { - builder.Append(" actions: "); - builder.AppendLine("["); - foreach (var item in AllowedActions) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DeniedActions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" notActions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(DeniedActions)) - { - if (DeniedActions.Any()) - { - builder.Append(" notActions: "); - builder.AppendLine("["); - foreach (var item in DeniedActions) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(AllowedDataActions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" dataActions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(AllowedDataActions)) - { - if (AllowedDataActions.Any()) - { - builder.Append(" dataActions: "); - builder.AppendLine("["); - foreach (var item in AllowedDataActions) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DeniedDataActions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" notDataActions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(DeniedDataActions)) - { - if (DeniedDataActions.Any()) - { - builder.Append(" notDataActions: "); - builder.AppendLine("["); - foreach (var item in DeniedDataActions) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(Permission)} does not support writing '{options.Format}' format."); - } - } - - Permission IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePermission(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(Permission)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/Permission.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/Permission.cs deleted file mode 100644 index 0b614bc2dd..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/Permission.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Role definition permissions. - public partial class Permission - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal Permission() - { - AllowedActions = new ChangeTrackingList(); - DeniedActions = new ChangeTrackingList(); - AllowedDataActions = new ChangeTrackingList(); - DeniedDataActions = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// Allowed actions. - /// Denied actions. - /// Allowed Data actions. - /// Denied Data actions. - /// Keeps track of any properties unknown to the library. - internal Permission(IReadOnlyList allowedActions, IReadOnlyList deniedActions, IReadOnlyList allowedDataActions, IReadOnlyList deniedDataActions, IDictionary serializedAdditionalRawData) - { - AllowedActions = allowedActions; - DeniedActions = deniedActions; - AllowedDataActions = allowedDataActions; - DeniedDataActions = deniedDataActions; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Allowed actions. - [WirePath("actions")] - public IReadOnlyList AllowedActions { get; } - /// Denied actions. - [WirePath("notActions")] - public IReadOnlyList DeniedActions { get; } - /// Allowed Data actions. - [WirePath("dataActions")] - public IReadOnlyList AllowedDataActions { get; } - /// Denied Data actions. - [WirePath("notDataActions")] - public IReadOnlyList DeniedDataActions { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentListResult.Serialization.cs deleted file mode 100644 index 3e3080735e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class PolicyAssignmentListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyAssignmentListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - PolicyAssignmentListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyAssignmentListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicyAssignmentListResult(document.RootElement, options); - } - - internal static PolicyAssignmentListResult DeserializePolicyAssignmentListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(PolicyAssignmentData.DeserializePolicyAssignmentData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicyAssignmentListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PolicyAssignmentListResult)} does not support writing '{options.Format}' format."); - } - } - - PolicyAssignmentListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicyAssignmentListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicyAssignmentListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentListResult.cs deleted file mode 100644 index 2c650f257a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of policy assignments. - internal partial class PolicyAssignmentListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal PolicyAssignmentListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of policy assignments. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal PolicyAssignmentListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of policy assignments. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentPatch.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentPatch.Serialization.cs deleted file mode 100644 index 57fee5d8fd..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentPatch.Serialization.cs +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class PolicyAssignmentPatch : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyAssignmentPatch)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Location)) - { - writer.WritePropertyName("location"u8); - writer.WriteStringValue(Location.Value); - } - if (Optional.IsDefined(Identity)) - { - writer.WritePropertyName("identity"u8); - JsonSerializer.Serialize(writer, Identity); - } - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (Optional.IsCollectionDefined(ResourceSelectors)) - { - writer.WritePropertyName("resourceSelectors"u8); - writer.WriteStartArray(); - foreach (var item in ResourceSelectors) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(Overrides)) - { - writer.WritePropertyName("overrides"u8); - writer.WriteStartArray(); - foreach (var item in Overrides) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - writer.WriteEndObject(); - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - PolicyAssignmentPatch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyAssignmentPatch)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicyAssignmentPatch(document.RootElement, options); - } - - internal static PolicyAssignmentPatch DeserializePolicyAssignmentPatch(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - AzureLocation? location = default; - ManagedServiceIdentity identity = default; - IList resourceSelectors = default; - IList overrides = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("location"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - location = new AzureLocation(property.Value.GetString()); - continue; - } - if (property.NameEquals("identity"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - identity = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("resourceSelectors"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(ResourceSelector.DeserializeResourceSelector(item, options)); - } - resourceSelectors = array; - continue; - } - if (property0.NameEquals("overrides"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(PolicyOverride.DeserializePolicyOverride(item, options)); - } - overrides = array; - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicyAssignmentPatch(location, identity, resourceSelectors ?? new ChangeTrackingList(), overrides ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(PolicyAssignmentPatch)} does not support writing '{options.Format}' format."); - } - } - - PolicyAssignmentPatch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicyAssignmentPatch(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicyAssignmentPatch)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentPatch.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentPatch.cs deleted file mode 100644 index d85c3fcbad..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentPatch.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The policy assignment for Patch request. - public partial class PolicyAssignmentPatch - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public PolicyAssignmentPatch() - { - ResourceSelectors = new ChangeTrackingList(); - Overrides = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The location of the policy assignment. Only required when utilizing managed identity. - /// The managed identity associated with the policy assignment. Current supported identity types: None, SystemAssigned, UserAssigned. - /// The resource selector list to filter policies by resource properties. - /// The policy property value override. - /// Keeps track of any properties unknown to the library. - internal PolicyAssignmentPatch(AzureLocation? location, ManagedServiceIdentity identity, IList resourceSelectors, IList overrides, IDictionary serializedAdditionalRawData) - { - Location = location; - Identity = identity; - ResourceSelectors = resourceSelectors; - Overrides = overrides; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The location of the policy assignment. Only required when utilizing managed identity. - [WirePath("location")] - public AzureLocation? Location { get; set; } - /// The managed identity associated with the policy assignment. Current supported identity types: None, SystemAssigned, UserAssigned. - [WirePath("identity")] - public ManagedServiceIdentity Identity { get; set; } - /// The resource selector list to filter policies by resource properties. - [WirePath("properties.resourceSelectors")] - public IList ResourceSelectors { get; } - /// The policy property value override. - [WirePath("properties.overrides")] - public IList Overrides { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionGroup.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionGroup.Serialization.cs deleted file mode 100644 index bcffda6463..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionGroup.Serialization.cs +++ /dev/null @@ -1,309 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class PolicyDefinitionGroup : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyDefinitionGroup)} does not support writing '{format}' format."); - } - - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (Optional.IsDefined(Category)) - { - writer.WritePropertyName("category"u8); - writer.WriteStringValue(Category); - } - if (Optional.IsDefined(Description)) - { - writer.WritePropertyName("description"u8); - writer.WriteStringValue(Description); - } - if (Optional.IsDefined(AdditionalMetadataId)) - { - writer.WritePropertyName("additionalMetadataId"u8); - writer.WriteStringValue(AdditionalMetadataId); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - PolicyDefinitionGroup IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyDefinitionGroup)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicyDefinitionGroup(document.RootElement, options); - } - - internal static PolicyDefinitionGroup DeserializePolicyDefinitionGroup(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - string displayName = default; - string category = default; - string description = default; - string additionalMetadataId = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (property.NameEquals("category"u8)) - { - category = property.Value.GetString(); - continue; - } - if (property.NameEquals("description"u8)) - { - description = property.Value.GetString(); - continue; - } - if (property.NameEquals("additionalMetadataId"u8)) - { - additionalMetadataId = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicyDefinitionGroup( - name, - displayName, - category, - description, - additionalMetadataId, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Category), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" category: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Category)) - { - builder.Append(" category: "); - if (Category.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Category}'''"); - } - else - { - builder.AppendLine($"'{Category}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Description), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" description: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Description)) - { - builder.Append(" description: "); - if (Description.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Description}'''"); - } - else - { - builder.AppendLine($"'{Description}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(AdditionalMetadataId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" additionalMetadataId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(AdditionalMetadataId)) - { - builder.Append(" additionalMetadataId: "); - if (AdditionalMetadataId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{AdditionalMetadataId}'''"); - } - else - { - builder.AppendLine($"'{AdditionalMetadataId}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PolicyDefinitionGroup)} does not support writing '{options.Format}' format."); - } - } - - PolicyDefinitionGroup IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicyDefinitionGroup(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicyDefinitionGroup)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionGroup.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionGroup.cs deleted file mode 100644 index 9f18d09866..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionGroup.cs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The policy definition group. - public partial class PolicyDefinitionGroup - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The name of the group. - /// is null. - public PolicyDefinitionGroup(string name) - { - Argument.AssertNotNull(name, nameof(name)); - - Name = name; - } - - /// Initializes a new instance of . - /// The name of the group. - /// The group's display name. - /// The group's category. - /// The group's description. - /// A resource ID of a resource that contains additional metadata about the group. - /// Keeps track of any properties unknown to the library. - internal PolicyDefinitionGroup(string name, string displayName, string category, string description, string additionalMetadataId, IDictionary serializedAdditionalRawData) - { - Name = name; - DisplayName = displayName; - Category = category; - Description = description; - AdditionalMetadataId = additionalMetadataId; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal PolicyDefinitionGroup() - { - } - - /// The name of the group. - [WirePath("name")] - public string Name { get; set; } - /// The group's display name. - [WirePath("displayName")] - public string DisplayName { get; set; } - /// The group's category. - [WirePath("category")] - public string Category { get; set; } - /// The group's description. - [WirePath("description")] - public string Description { get; set; } - /// A resource ID of a resource that contains additional metadata about the group. - [WirePath("additionalMetadataId")] - public string AdditionalMetadataId { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionListResult.Serialization.cs deleted file mode 100644 index f0b97f4bac..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class PolicyDefinitionListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyDefinitionListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - PolicyDefinitionListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyDefinitionListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicyDefinitionListResult(document.RootElement, options); - } - - internal static PolicyDefinitionListResult DeserializePolicyDefinitionListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(PolicyDefinitionData.DeserializePolicyDefinitionData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicyDefinitionListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PolicyDefinitionListResult)} does not support writing '{options.Format}' format."); - } - } - - PolicyDefinitionListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicyDefinitionListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicyDefinitionListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionListResult.cs deleted file mode 100644 index c09165e0d9..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of policy definitions. - internal partial class PolicyDefinitionListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal PolicyDefinitionListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of policy definitions. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal PolicyDefinitionListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of policy definitions. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionReference.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionReference.Serialization.cs deleted file mode 100644 index c1d6ceb7ba..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionReference.Serialization.cs +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class PolicyDefinitionReference : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyDefinitionReference)} does not support writing '{format}' format."); - } - - writer.WritePropertyName("policyDefinitionId"u8); - writer.WriteStringValue(PolicyDefinitionId); - if (Optional.IsCollectionDefined(Parameters)) - { - writer.WritePropertyName("parameters"u8); - writer.WriteStartObject(); - foreach (var item in Parameters) - { - writer.WritePropertyName(item.Key); - writer.WriteObjectValue(item.Value, options); - } - writer.WriteEndObject(); - } - if (Optional.IsDefined(PolicyDefinitionReferenceId)) - { - writer.WritePropertyName("policyDefinitionReferenceId"u8); - writer.WriteStringValue(PolicyDefinitionReferenceId); - } - if (Optional.IsCollectionDefined(GroupNames)) - { - writer.WritePropertyName("groupNames"u8); - writer.WriteStartArray(); - foreach (var item in GroupNames) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - PolicyDefinitionReference IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyDefinitionReference)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicyDefinitionReference(document.RootElement, options); - } - - internal static PolicyDefinitionReference DeserializePolicyDefinitionReference(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string policyDefinitionId = default; - IDictionary parameters = default; - string policyDefinitionReferenceId = default; - IList groupNames = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("policyDefinitionId"u8)) - { - policyDefinitionId = property.Value.GetString(); - continue; - } - if (property.NameEquals("parameters"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, ArmPolicyParameterValue.DeserializeArmPolicyParameterValue(property0.Value, options)); - } - parameters = dictionary; - continue; - } - if (property.NameEquals("policyDefinitionReferenceId"u8)) - { - policyDefinitionReferenceId = property.Value.GetString(); - continue; - } - if (property.NameEquals("groupNames"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - groupNames = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicyDefinitionReference(policyDefinitionId, parameters ?? new ChangeTrackingDictionary(), policyDefinitionReferenceId, groupNames ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyDefinitionId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyDefinitionId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PolicyDefinitionId)) - { - builder.Append(" policyDefinitionId: "); - if (PolicyDefinitionId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{PolicyDefinitionId}'''"); - } - else - { - builder.AppendLine($"'{PolicyDefinitionId}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Parameters), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parameters: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Parameters)) - { - if (Parameters.Any()) - { - builder.Append(" parameters: "); - builder.AppendLine("{"); - foreach (var item in Parameters) - { - builder.Append($" '{item.Key}': "); - BicepSerializationHelpers.AppendChildObject(builder, item.Value, options, 4, false, " parameters: "); - } - builder.AppendLine(" }"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyDefinitionReferenceId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyDefinitionReferenceId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PolicyDefinitionReferenceId)) - { - builder.Append(" policyDefinitionReferenceId: "); - if (PolicyDefinitionReferenceId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{PolicyDefinitionReferenceId}'''"); - } - else - { - builder.AppendLine($"'{PolicyDefinitionReferenceId}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(GroupNames), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" groupNames: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(GroupNames)) - { - if (GroupNames.Any()) - { - builder.Append(" groupNames: "); - builder.AppendLine("["); - foreach (var item in GroupNames) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PolicyDefinitionReference)} does not support writing '{options.Format}' format."); - } - } - - PolicyDefinitionReference IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicyDefinitionReference(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicyDefinitionReference)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionReference.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionReference.cs deleted file mode 100644 index da023f91ac..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionReference.cs +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The policy definition reference. - public partial class PolicyDefinitionReference - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The ID of the policy definition or policy set definition. - /// is null. - public PolicyDefinitionReference(string policyDefinitionId) - { - Argument.AssertNotNull(policyDefinitionId, nameof(policyDefinitionId)); - - PolicyDefinitionId = policyDefinitionId; - Parameters = new ChangeTrackingDictionary(); - GroupNames = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The ID of the policy definition or policy set definition. - /// The parameter values for the referenced policy rule. The keys are the parameter names. - /// A unique id (within the policy set definition) for this policy definition reference. - /// The name of the groups that this policy definition reference belongs to. - /// Keeps track of any properties unknown to the library. - internal PolicyDefinitionReference(string policyDefinitionId, IDictionary parameters, string policyDefinitionReferenceId, IList groupNames, IDictionary serializedAdditionalRawData) - { - PolicyDefinitionId = policyDefinitionId; - Parameters = parameters; - PolicyDefinitionReferenceId = policyDefinitionReferenceId; - GroupNames = groupNames; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal PolicyDefinitionReference() - { - } - - /// The ID of the policy definition or policy set definition. - [WirePath("policyDefinitionId")] - public string PolicyDefinitionId { get; set; } - /// The parameter values for the referenced policy rule. The keys are the parameter names. - [WirePath("parameters")] - public IDictionary Parameters { get; } - /// A unique id (within the policy set definition) for this policy definition reference. - [WirePath("policyDefinitionReferenceId")] - public string PolicyDefinitionReferenceId { get; set; } - /// The name of the groups that this policy definition reference belongs to. - [WirePath("groupNames")] - public IList GroupNames { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverride.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverride.Serialization.cs deleted file mode 100644 index ac3756baff..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverride.Serialization.cs +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class PolicyOverride : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyOverride)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Kind)) - { - writer.WritePropertyName("kind"u8); - writer.WriteStringValue(Kind.Value.ToString()); - } - if (Optional.IsDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStringValue(Value); - } - if (Optional.IsCollectionDefined(Selectors)) - { - writer.WritePropertyName("selectors"u8); - writer.WriteStartArray(); - foreach (var item in Selectors) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - PolicyOverride IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyOverride)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicyOverride(document.RootElement, options); - } - - internal static PolicyOverride DeserializePolicyOverride(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - PolicyOverrideKind? kind = default; - string value = default; - IList selectors = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("kind"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - kind = new PolicyOverrideKind(property.Value.GetString()); - continue; - } - if (property.NameEquals("value"u8)) - { - value = property.Value.GetString(); - continue; - } - if (property.NameEquals("selectors"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ResourceSelectorExpression.DeserializeResourceSelectorExpression(item, options)); - } - selectors = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicyOverride(kind, value, selectors ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Kind), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" kind: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Kind)) - { - builder.Append(" kind: "); - builder.AppendLine($"'{Kind.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Value)) - { - builder.Append(" value: "); - if (Value.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Value}'''"); - } - else - { - builder.AppendLine($"'{Value}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Selectors), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" selectors: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Selectors)) - { - if (Selectors.Any()) - { - builder.Append(" selectors: "); - builder.AppendLine("["); - foreach (var item in Selectors) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " selectors: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PolicyOverride)} does not support writing '{options.Format}' format."); - } - } - - PolicyOverride IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicyOverride(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicyOverride)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverride.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverride.cs deleted file mode 100644 index d546bbcfa3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverride.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The policy property value override. - public partial class PolicyOverride - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public PolicyOverride() - { - Selectors = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The override kind. - /// The value to override the policy property. - /// The list of the selector expressions. - /// Keeps track of any properties unknown to the library. - internal PolicyOverride(PolicyOverrideKind? kind, string value, IList selectors, IDictionary serializedAdditionalRawData) - { - Kind = kind; - Value = value; - Selectors = selectors; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The override kind. - [WirePath("kind")] - public PolicyOverrideKind? Kind { get; set; } - /// The value to override the policy property. - [WirePath("value")] - public string Value { get; set; } - /// The list of the selector expressions. - [WirePath("selectors")] - public IList Selectors { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverrideKind.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverrideKind.cs deleted file mode 100644 index 1529755b23..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverrideKind.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The override kind. - public readonly partial struct PolicyOverrideKind : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public PolicyOverrideKind(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string PolicyEffectValue = "policyEffect"; - - /// It will override the policy effect type. - public static PolicyOverrideKind PolicyEffect { get; } = new PolicyOverrideKind(PolicyEffectValue); - /// Determines if two values are the same. - public static bool operator ==(PolicyOverrideKind left, PolicyOverrideKind right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(PolicyOverrideKind left, PolicyOverrideKind right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator PolicyOverrideKind(string value) => new PolicyOverrideKind(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is PolicyOverrideKind other && Equals(other); - /// - public bool Equals(PolicyOverrideKind other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicySetDefinitionListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicySetDefinitionListResult.Serialization.cs deleted file mode 100644 index dd8370379d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicySetDefinitionListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class PolicySetDefinitionListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicySetDefinitionListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - PolicySetDefinitionListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicySetDefinitionListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicySetDefinitionListResult(document.RootElement, options); - } - - internal static PolicySetDefinitionListResult DeserializePolicySetDefinitionListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(PolicySetDefinitionData.DeserializePolicySetDefinitionData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicySetDefinitionListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PolicySetDefinitionListResult)} does not support writing '{options.Format}' format."); - } - } - - PolicySetDefinitionListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicySetDefinitionListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicySetDefinitionListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicySetDefinitionListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicySetDefinitionListResult.cs deleted file mode 100644 index 7077003141..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicySetDefinitionListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of policy set definitions. - internal partial class PolicySetDefinitionListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal PolicySetDefinitionListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of policy set definitions. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal PolicySetDefinitionListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of policy set definitions. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyType.cs deleted file mode 100644 index 9f88c1c72e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PolicyType.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static. - public readonly partial struct PolicyType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public PolicyType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string NotSpecifiedValue = "NotSpecified"; - private const string BuiltInValue = "BuiltIn"; - private const string CustomValue = "Custom"; - private const string StaticValue = "Static"; - - /// NotSpecified. - public static PolicyType NotSpecified { get; } = new PolicyType(NotSpecifiedValue); - /// BuiltIn. - public static PolicyType BuiltIn { get; } = new PolicyType(BuiltInValue); - /// Custom. - public static PolicyType Custom { get; } = new PolicyType(CustomValue); - /// Static. - public static PolicyType Static { get; } = new PolicyType(StaticValue); - /// Determines if two values are the same. - public static bool operator ==(PolicyType left, PolicyType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(PolicyType left, PolicyType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator PolicyType(string value) => new PolicyType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is PolicyType other && Equals(other); - /// - public bool Equals(PolicyType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTag.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTag.Serialization.cs deleted file mode 100644 index 40ff878479..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTag.Serialization.cs +++ /dev/null @@ -1,283 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class PredefinedTag : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PredefinedTag)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (Optional.IsDefined(TagName)) - { - writer.WritePropertyName("tagName"u8); - writer.WriteStringValue(TagName); - } - if (Optional.IsDefined(Count)) - { - writer.WritePropertyName("count"u8); - writer.WriteObjectValue(Count, options); - } - if (Optional.IsCollectionDefined(Values)) - { - writer.WritePropertyName("values"u8); - writer.WriteStartArray(); - foreach (var item in Values) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - PredefinedTag IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PredefinedTag)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePredefinedTag(document.RootElement, options); - } - - internal static PredefinedTag DeserializePredefinedTag(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string id = default; - string tagName = default; - PredefinedTagCount count = default; - IReadOnlyList values = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("tagName"u8)) - { - tagName = property.Value.GetString(); - continue; - } - if (property.NameEquals("count"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - count = PredefinedTagCount.DeserializePredefinedTagCount(property.Value, options); - continue; - } - if (property.NameEquals("values"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(PredefinedTagValue.DeserializePredefinedTagValue(item, options)); - } - values = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PredefinedTag(id, tagName, count, values ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - if (Id.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Id}'''"); - } - else - { - builder.AppendLine($"'{Id}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TagName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tagName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TagName)) - { - builder.Append(" tagName: "); - if (TagName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{TagName}'''"); - } - else - { - builder.AppendLine($"'{TagName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Count), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" count: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Count)) - { - builder.Append(" count: "); - BicepSerializationHelpers.AppendChildObject(builder, Count, options, 2, false, " count: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Values), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" values: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Values)) - { - if (Values.Any()) - { - builder.Append(" values: "); - builder.AppendLine("["); - foreach (var item in Values) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " values: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PredefinedTag)} does not support writing '{options.Format}' format."); - } - } - - PredefinedTag IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePredefinedTag(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PredefinedTag)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTag.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTag.cs deleted file mode 100644 index a929577cd8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTag.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Tag details. - public partial class PredefinedTag - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal PredefinedTag() - { - Values = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The tag name ID. - /// The tag name. - /// The total number of resources that use the resource tag. When a tag is initially created and has no associated resources, the value is 0. - /// The list of tag values. - /// Keeps track of any properties unknown to the library. - internal PredefinedTag(string id, string tagName, PredefinedTagCount count, IReadOnlyList values, IDictionary serializedAdditionalRawData) - { - Id = id; - TagName = tagName; - Count = count; - Values = values; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The tag name ID. - [WirePath("id")] - public string Id { get; } - /// The tag name. - [WirePath("tagName")] - public string TagName { get; } - /// The total number of resources that use the resource tag. When a tag is initially created and has no associated resources, the value is 0. - [WirePath("count")] - public PredefinedTagCount Count { get; } - /// The list of tag values. - [WirePath("values")] - public IReadOnlyList Values { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagCount.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagCount.Serialization.cs deleted file mode 100644 index 0b640a7ed9..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagCount.Serialization.cs +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class PredefinedTagCount : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PredefinedTagCount)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(PredefinedTagCountType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(PredefinedTagCountType); - } - if (Optional.IsDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteNumberValue(Value.Value); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - PredefinedTagCount IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PredefinedTagCount)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePredefinedTagCount(document.RootElement, options); - } - - internal static PredefinedTagCount DeserializePredefinedTagCount(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string type = default; - int? value = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - value = property.Value.GetInt32(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PredefinedTagCount(type, value, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PredefinedTagCountType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" type: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PredefinedTagCountType)) - { - builder.Append(" type: "); - if (PredefinedTagCountType.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{PredefinedTagCountType}'''"); - } - else - { - builder.AppendLine($"'{PredefinedTagCountType}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Value)) - { - builder.Append(" value: "); - builder.AppendLine($"{Value.Value}"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PredefinedTagCount)} does not support writing '{options.Format}' format."); - } - } - - PredefinedTagCount IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePredefinedTagCount(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PredefinedTagCount)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagCount.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagCount.cs deleted file mode 100644 index b7d6360ac8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagCount.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Tag count. - public partial class PredefinedTagCount - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal PredefinedTagCount() - { - } - - /// Initializes a new instance of . - /// Type of count. - /// Value of count. - /// Keeps track of any properties unknown to the library. - internal PredefinedTagCount(string predefinedTagCountType, int? value, IDictionary serializedAdditionalRawData) - { - PredefinedTagCountType = predefinedTagCountType; - Value = value; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Type of count. - [WirePath("type")] - public string PredefinedTagCountType { get; } - /// Value of count. - [WirePath("value")] - public int? Value { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagValue.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagValue.Serialization.cs deleted file mode 100644 index 53ab84ffc9..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagValue.Serialization.cs +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class PredefinedTagValue : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PredefinedTagValue)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (Optional.IsDefined(TagValue)) - { - writer.WritePropertyName("tagValue"u8); - writer.WriteStringValue(TagValue); - } - if (Optional.IsDefined(Count)) - { - writer.WritePropertyName("count"u8); - writer.WriteObjectValue(Count, options); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - PredefinedTagValue IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PredefinedTagValue)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePredefinedTagValue(document.RootElement, options); - } - - internal static PredefinedTagValue DeserializePredefinedTagValue(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string id = default; - string tagValue = default; - PredefinedTagCount count = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("tagValue"u8)) - { - tagValue = property.Value.GetString(); - continue; - } - if (property.NameEquals("count"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - count = PredefinedTagCount.DeserializePredefinedTagCount(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PredefinedTagValue(id, tagValue, count, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - if (Id.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Id}'''"); - } - else - { - builder.AppendLine($"'{Id}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TagValue), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tagValue: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TagValue)) - { - builder.Append(" tagValue: "); - if (TagValue.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{TagValue}'''"); - } - else - { - builder.AppendLine($"'{TagValue}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Count), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" count: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Count)) - { - builder.Append(" count: "); - BicepSerializationHelpers.AppendChildObject(builder, Count, options, 2, false, " count: "); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PredefinedTagValue)} does not support writing '{options.Format}' format."); - } - } - - PredefinedTagValue IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePredefinedTagValue(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PredefinedTagValue)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagValue.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagValue.cs deleted file mode 100644 index 7c91e6cc59..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagValue.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Tag information. - public partial class PredefinedTagValue - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal PredefinedTagValue() - { - } - - /// Initializes a new instance of . - /// The tag value ID. - /// The tag value. - /// The tag value count. - /// Keeps track of any properties unknown to the library. - internal PredefinedTagValue(string id, string tagValue, PredefinedTagCount count, IDictionary serializedAdditionalRawData) - { - Id = id; - TagValue = tagValue; - Count = count; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The tag value ID. - [WirePath("id")] - public string Id { get; } - /// The tag value. - [WirePath("tagValue")] - public string TagValue { get; } - /// The tag value count. - [WirePath("count")] - public PredefinedTagCount Count { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagsListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagsListResult.Serialization.cs deleted file mode 100644 index d3a49bc520..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagsListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class PredefinedTagsListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PredefinedTagsListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - PredefinedTagsListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PredefinedTagsListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePredefinedTagsListResult(document.RootElement, options); - } - - internal static PredefinedTagsListResult DeserializePredefinedTagsListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(PredefinedTag.DeserializePredefinedTag(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PredefinedTagsListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PredefinedTagsListResult)} does not support writing '{options.Format}' format."); - } - } - - PredefinedTagsListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePredefinedTagsListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PredefinedTagsListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagsListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagsListResult.cs deleted file mode 100644 index dc4cc163ff..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagsListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of subscription tags. - internal partial class PredefinedTagsListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal PredefinedTagsListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of tags. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal PredefinedTagsListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of tags. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderAuthorizationConsentState.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderAuthorizationConsentState.cs deleted file mode 100644 index 70a7ad1aa3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderAuthorizationConsentState.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The provider authorization consent state. - public readonly partial struct ProviderAuthorizationConsentState : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ProviderAuthorizationConsentState(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string NotSpecifiedValue = "NotSpecified"; - private const string RequiredValue = "Required"; - private const string NotRequiredValue = "NotRequired"; - private const string ConsentedValue = "Consented"; - - /// NotSpecified. - public static ProviderAuthorizationConsentState NotSpecified { get; } = new ProviderAuthorizationConsentState(NotSpecifiedValue); - /// Required. - public static ProviderAuthorizationConsentState Required { get; } = new ProviderAuthorizationConsentState(RequiredValue); - /// NotRequired. - public static ProviderAuthorizationConsentState NotRequired { get; } = new ProviderAuthorizationConsentState(NotRequiredValue); - /// Consented. - public static ProviderAuthorizationConsentState Consented { get; } = new ProviderAuthorizationConsentState(ConsentedValue); - /// Determines if two values are the same. - public static bool operator ==(ProviderAuthorizationConsentState left, ProviderAuthorizationConsentState right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ProviderAuthorizationConsentState left, ProviderAuthorizationConsentState right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ProviderAuthorizationConsentState(string value) => new ProviderAuthorizationConsentState(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ProviderAuthorizationConsentState other && Equals(other); - /// - public bool Equals(ProviderAuthorizationConsentState other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderConsentDefinition.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderConsentDefinition.Serialization.cs deleted file mode 100644 index 3dcd030070..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderConsentDefinition.Serialization.cs +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class ProviderConsentDefinition : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderConsentDefinition)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(ConsentToAuthorization)) - { - writer.WritePropertyName("consentToAuthorization"u8); - writer.WriteBooleanValue(ConsentToAuthorization.Value); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ProviderConsentDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderConsentDefinition)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeProviderConsentDefinition(document.RootElement, options); - } - - internal static ProviderConsentDefinition DeserializeProviderConsentDefinition(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - bool? consentToAuthorization = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("consentToAuthorization"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - consentToAuthorization = property.Value.GetBoolean(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ProviderConsentDefinition(consentToAuthorization, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ProviderConsentDefinition)} does not support writing '{options.Format}' format."); - } - } - - ProviderConsentDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeProviderConsentDefinition(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ProviderConsentDefinition)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderConsentDefinition.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderConsentDefinition.cs deleted file mode 100644 index 92b4c29858..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderConsentDefinition.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The provider consent. - internal partial class ProviderConsentDefinition - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ProviderConsentDefinition() - { - } - - /// Initializes a new instance of . - /// A value indicating whether authorization is consented or not. - /// Keeps track of any properties unknown to the library. - internal ProviderConsentDefinition(bool? consentToAuthorization, IDictionary serializedAdditionalRawData) - { - ConsentToAuthorization = consentToAuthorization; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// A value indicating whether authorization is consented or not. - [WirePath("consentToAuthorization")] - public bool? ConsentToAuthorization { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderExtendedLocation.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderExtendedLocation.Serialization.cs deleted file mode 100644 index f6edb22cb3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderExtendedLocation.Serialization.cs +++ /dev/null @@ -1,262 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ProviderExtendedLocation : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderExtendedLocation)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Location)) - { - writer.WritePropertyName("location"u8); - writer.WriteStringValue(Location.Value); - } - if (Optional.IsDefined(ProviderExtendedLocationType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ProviderExtendedLocationType); - } - if (Optional.IsCollectionDefined(ExtendedLocations)) - { - writer.WritePropertyName("extendedLocations"u8); - writer.WriteStartArray(); - foreach (var item in ExtendedLocations) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ProviderExtendedLocation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderExtendedLocation)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeProviderExtendedLocation(document.RootElement, options); - } - - internal static ProviderExtendedLocation DeserializeProviderExtendedLocation(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - AzureLocation? location = default; - string type = default; - IReadOnlyList extendedLocations = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("location"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - location = new AzureLocation(property.Value.GetString()); - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (property.NameEquals("extendedLocations"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - extendedLocations = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ProviderExtendedLocation(location, type, extendedLocations ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Location), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" location: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Location)) - { - builder.Append(" location: "); - builder.AppendLine($"'{Location.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ProviderExtendedLocationType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" type: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ProviderExtendedLocationType)) - { - builder.Append(" type: "); - if (ProviderExtendedLocationType.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ProviderExtendedLocationType}'''"); - } - else - { - builder.AppendLine($"'{ProviderExtendedLocationType}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ExtendedLocations), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" extendedLocations: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ExtendedLocations)) - { - if (ExtendedLocations.Any()) - { - builder.Append(" extendedLocations: "); - builder.AppendLine("["); - foreach (var item in ExtendedLocations) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ProviderExtendedLocation)} does not support writing '{options.Format}' format."); - } - } - - ProviderExtendedLocation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeProviderExtendedLocation(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ProviderExtendedLocation)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderExtendedLocation.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderExtendedLocation.cs deleted file mode 100644 index 3b129aeeb0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderExtendedLocation.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The provider extended location. - public partial class ProviderExtendedLocation - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ProviderExtendedLocation() - { - ExtendedLocations = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The azure location. - /// The extended location type. - /// The extended locations for the azure location. - /// Keeps track of any properties unknown to the library. - internal ProviderExtendedLocation(AzureLocation? location, string providerExtendedLocationType, IReadOnlyList extendedLocations, IDictionary serializedAdditionalRawData) - { - Location = location; - ProviderExtendedLocationType = providerExtendedLocationType; - ExtendedLocations = extendedLocations; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The azure location. - [WirePath("location")] - public AzureLocation? Location { get; } - /// The extended location type. - [WirePath("type")] - public string ProviderExtendedLocationType { get; } - /// The extended locations for the azure location. - [WirePath("extendedLocations")] - public IReadOnlyList ExtendedLocations { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermission.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermission.Serialization.cs deleted file mode 100644 index 25e7bc3b01..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermission.Serialization.cs +++ /dev/null @@ -1,260 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ProviderPermission : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderPermission)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(ApplicationId)) - { - writer.WritePropertyName("applicationId"u8); - writer.WriteStringValue(ApplicationId); - } - if (Optional.IsDefined(RoleDefinition)) - { - writer.WritePropertyName("roleDefinition"u8); - writer.WriteObjectValue(RoleDefinition, options); - } - if (Optional.IsDefined(ManagedByRoleDefinition)) - { - writer.WritePropertyName("managedByRoleDefinition"u8); - writer.WriteObjectValue(ManagedByRoleDefinition, options); - } - if (Optional.IsDefined(ProviderAuthorizationConsentState)) - { - writer.WritePropertyName("providerAuthorizationConsentState"u8); - writer.WriteStringValue(ProviderAuthorizationConsentState.Value.ToString()); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ProviderPermission IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderPermission)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeProviderPermission(document.RootElement, options); - } - - internal static ProviderPermission DeserializeProviderPermission(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string applicationId = default; - AzureRoleDefinition roleDefinition = default; - AzureRoleDefinition managedByRoleDefinition = default; - ProviderAuthorizationConsentState? providerAuthorizationConsentState = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("applicationId"u8)) - { - applicationId = property.Value.GetString(); - continue; - } - if (property.NameEquals("roleDefinition"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - roleDefinition = AzureRoleDefinition.DeserializeAzureRoleDefinition(property.Value, options); - continue; - } - if (property.NameEquals("managedByRoleDefinition"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - managedByRoleDefinition = AzureRoleDefinition.DeserializeAzureRoleDefinition(property.Value, options); - continue; - } - if (property.NameEquals("providerAuthorizationConsentState"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - providerAuthorizationConsentState = new ProviderAuthorizationConsentState(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ProviderPermission(applicationId, roleDefinition, managedByRoleDefinition, providerAuthorizationConsentState, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ApplicationId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" applicationId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ApplicationId)) - { - builder.Append(" applicationId: "); - if (ApplicationId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ApplicationId}'''"); - } - else - { - builder.AppendLine($"'{ApplicationId}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(RoleDefinition), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" roleDefinition: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(RoleDefinition)) - { - builder.Append(" roleDefinition: "); - BicepSerializationHelpers.AppendChildObject(builder, RoleDefinition, options, 2, false, " roleDefinition: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ManagedByRoleDefinition), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" managedByRoleDefinition: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ManagedByRoleDefinition)) - { - builder.Append(" managedByRoleDefinition: "); - BicepSerializationHelpers.AppendChildObject(builder, ManagedByRoleDefinition, options, 2, false, " managedByRoleDefinition: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ProviderAuthorizationConsentState), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" providerAuthorizationConsentState: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ProviderAuthorizationConsentState)) - { - builder.Append(" providerAuthorizationConsentState: "); - builder.AppendLine($"'{ProviderAuthorizationConsentState.Value.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ProviderPermission)} does not support writing '{options.Format}' format."); - } - } - - ProviderPermission IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeProviderPermission(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ProviderPermission)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermission.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermission.cs deleted file mode 100644 index b8dbd24538..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermission.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The provider permission. - public partial class ProviderPermission - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ProviderPermission() - { - } - - /// Initializes a new instance of . - /// The application id. - /// Role definition properties. - /// Role definition properties. - /// The provider authorization consent state. - /// Keeps track of any properties unknown to the library. - internal ProviderPermission(string applicationId, AzureRoleDefinition roleDefinition, AzureRoleDefinition managedByRoleDefinition, ProviderAuthorizationConsentState? providerAuthorizationConsentState, IDictionary serializedAdditionalRawData) - { - ApplicationId = applicationId; - RoleDefinition = roleDefinition; - ManagedByRoleDefinition = managedByRoleDefinition; - ProviderAuthorizationConsentState = providerAuthorizationConsentState; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The application id. - [WirePath("applicationId")] - public string ApplicationId { get; } - /// Role definition properties. - [WirePath("roleDefinition")] - public AzureRoleDefinition RoleDefinition { get; } - /// Role definition properties. - [WirePath("managedByRoleDefinition")] - public AzureRoleDefinition ManagedByRoleDefinition { get; } - /// The provider authorization consent state. - [WirePath("providerAuthorizationConsentState")] - public ProviderAuthorizationConsentState? ProviderAuthorizationConsentState { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermissionListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermissionListResult.Serialization.cs deleted file mode 100644 index c2577692c4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermissionListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class ProviderPermissionListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderPermissionListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ProviderPermissionListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderPermissionListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeProviderPermissionListResult(document.RootElement, options); - } - - internal static ProviderPermissionListResult DeserializeProviderPermissionListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ProviderPermission.DeserializeProviderPermission(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ProviderPermissionListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ProviderPermissionListResult)} does not support writing '{options.Format}' format."); - } - } - - ProviderPermissionListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeProviderPermissionListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ProviderPermissionListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermissionListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermissionListResult.cs deleted file mode 100644 index bfb5b6bbb2..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermissionListResult.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of provider permissions. - internal partial class ProviderPermissionListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ProviderPermissionListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of provider permissions. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal ProviderPermissionListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of provider permissions. - [WirePath("value")] - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - [WirePath("nextLink")] - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderRegistrationContent.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderRegistrationContent.Serialization.cs deleted file mode 100644 index bf15b0087f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderRegistrationContent.Serialization.cs +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ProviderRegistrationContent : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderRegistrationContent)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(ThirdPartyProviderConsent)) - { - writer.WritePropertyName("thirdPartyProviderConsent"u8); - writer.WriteObjectValue(ThirdPartyProviderConsent, options); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ProviderRegistrationContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderRegistrationContent)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeProviderRegistrationContent(document.RootElement, options); - } - - internal static ProviderRegistrationContent DeserializeProviderRegistrationContent(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ProviderConsentDefinition thirdPartyProviderConsent = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("thirdPartyProviderConsent"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - thirdPartyProviderConsent = ProviderConsentDefinition.DeserializeProviderConsentDefinition(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ProviderRegistrationContent(thirdPartyProviderConsent, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ProviderRegistrationContent)} does not support writing '{options.Format}' format."); - } - } - - ProviderRegistrationContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeProviderRegistrationContent(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ProviderRegistrationContent)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderRegistrationContent.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderRegistrationContent.cs deleted file mode 100644 index 92eb16dbd6..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderRegistrationContent.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The provider registration definition. - public partial class ProviderRegistrationContent - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ProviderRegistrationContent() - { - } - - /// Initializes a new instance of . - /// The provider consent. - /// Keeps track of any properties unknown to the library. - internal ProviderRegistrationContent(ProviderConsentDefinition thirdPartyProviderConsent, IDictionary serializedAdditionalRawData) - { - ThirdPartyProviderConsent = thirdPartyProviderConsent; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The provider consent. - internal ProviderConsentDefinition ThirdPartyProviderConsent { get; set; } - /// A value indicating whether authorization is consented or not. - [WirePath("thirdPartyProviderConsent.consentToAuthorization")] - public bool? ConsentToAuthorization - { - get => ThirdPartyProviderConsent is null ? default : ThirdPartyProviderConsent.ConsentToAuthorization; - set - { - if (ThirdPartyProviderConsent is null) - ThirdPartyProviderConsent = new ProviderConsentDefinition(); - ThirdPartyProviderConsent.ConsentToAuthorization = value; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceType.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceType.Serialization.cs deleted file mode 100644 index 2aec022a34..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceType.Serialization.cs +++ /dev/null @@ -1,627 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ProviderResourceType : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderResourceType)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(ResourceType)) - { - writer.WritePropertyName("resourceType"u8); - writer.WriteStringValue(ResourceType); - } - if (Optional.IsCollectionDefined(Locations)) - { - writer.WritePropertyName("locations"u8); - writer.WriteStartArray(); - foreach (var item in Locations) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(LocationMappings)) - { - writer.WritePropertyName("locationMappings"u8); - writer.WriteStartArray(); - foreach (var item in LocationMappings) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(Aliases)) - { - writer.WritePropertyName("aliases"u8); - writer.WriteStartArray(); - foreach (var item in Aliases) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(ApiVersions)) - { - writer.WritePropertyName("apiVersions"u8); - writer.WriteStartArray(); - foreach (var item in ApiVersions) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(DefaultApiVersion)) - { - writer.WritePropertyName("defaultApiVersion"u8); - writer.WriteStringValue(DefaultApiVersion); - } - if (Optional.IsCollectionDefined(ZoneMappings)) - { - writer.WritePropertyName("zoneMappings"u8); - writer.WriteStartArray(); - foreach (var item in ZoneMappings) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsCollectionDefined(ApiProfiles)) - { - writer.WritePropertyName("apiProfiles"u8); - writer.WriteStartArray(); - foreach (var item in ApiProfiles) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(Capabilities)) - { - writer.WritePropertyName("capabilities"u8); - writer.WriteStringValue(Capabilities); - } - if (Optional.IsCollectionDefined(Properties)) - { - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - foreach (var item in Properties) - { - writer.WritePropertyName(item.Key); - writer.WriteStringValue(item.Value); - } - writer.WriteEndObject(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ProviderResourceType IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderResourceType)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeProviderResourceType(document.RootElement, options); - } - - internal static ProviderResourceType DeserializeProviderResourceType(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string resourceType = default; - IReadOnlyList locations = default; - IReadOnlyList locationMappings = default; - IReadOnlyList aliases = default; - IReadOnlyList apiVersions = default; - string defaultApiVersion = default; - IReadOnlyList zoneMappings = default; - IReadOnlyList apiProfiles = default; - string capabilities = default; - IReadOnlyDictionary properties = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("resourceType"u8)) - { - resourceType = property.Value.GetString(); - continue; - } - if (property.NameEquals("locations"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - locations = array; - continue; - } - if (property.NameEquals("locationMappings"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ProviderExtendedLocation.DeserializeProviderExtendedLocation(item, options)); - } - locationMappings = array; - continue; - } - if (property.NameEquals("aliases"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ResourceTypeAlias.DeserializeResourceTypeAlias(item, options)); - } - aliases = array; - continue; - } - if (property.NameEquals("apiVersions"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - apiVersions = array; - continue; - } - if (property.NameEquals("defaultApiVersion"u8)) - { - defaultApiVersion = property.Value.GetString(); - continue; - } - if (property.NameEquals("zoneMappings"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ZoneMapping.DeserializeZoneMapping(item, options)); - } - zoneMappings = array; - continue; - } - if (property.NameEquals("apiProfiles"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ApiProfile.DeserializeApiProfile(item, options)); - } - apiProfiles = array; - continue; - } - if (property.NameEquals("capabilities"u8)) - { - capabilities = property.Value.GetString(); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - properties = dictionary; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ProviderResourceType( - resourceType, - locations ?? new ChangeTrackingList(), - locationMappings ?? new ChangeTrackingList(), - aliases ?? new ChangeTrackingList(), - apiVersions ?? new ChangeTrackingList(), - defaultApiVersion, - zoneMappings ?? new ChangeTrackingList(), - apiProfiles ?? new ChangeTrackingList(), - capabilities, - properties ?? new ChangeTrackingDictionary(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ResourceType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" resourceType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ResourceType)) - { - builder.Append(" resourceType: "); - if (ResourceType.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ResourceType}'''"); - } - else - { - builder.AppendLine($"'{ResourceType}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Locations), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" locations: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Locations)) - { - if (Locations.Any()) - { - builder.Append(" locations: "); - builder.AppendLine("["); - foreach (var item in Locations) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(LocationMappings), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" locationMappings: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(LocationMappings)) - { - if (LocationMappings.Any()) - { - builder.Append(" locationMappings: "); - builder.AppendLine("["); - foreach (var item in LocationMappings) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " locationMappings: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Aliases), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" aliases: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Aliases)) - { - if (Aliases.Any()) - { - builder.Append(" aliases: "); - builder.AppendLine("["); - foreach (var item in Aliases) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " aliases: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ApiVersions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" apiVersions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ApiVersions)) - { - if (ApiVersions.Any()) - { - builder.Append(" apiVersions: "); - builder.AppendLine("["); - foreach (var item in ApiVersions) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DefaultApiVersion), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" defaultApiVersion: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DefaultApiVersion)) - { - builder.Append(" defaultApiVersion: "); - if (DefaultApiVersion.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DefaultApiVersion}'''"); - } - else - { - builder.AppendLine($"'{DefaultApiVersion}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ZoneMappings), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" zoneMappings: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ZoneMappings)) - { - if (ZoneMappings.Any()) - { - builder.Append(" zoneMappings: "); - builder.AppendLine("["); - foreach (var item in ZoneMappings) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " zoneMappings: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ApiProfiles), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" apiProfiles: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ApiProfiles)) - { - if (ApiProfiles.Any()) - { - builder.Append(" apiProfiles: "); - builder.AppendLine("["); - foreach (var item in ApiProfiles) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " apiProfiles: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Capabilities), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" capabilities: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Capabilities)) - { - builder.Append(" capabilities: "); - if (Capabilities.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Capabilities}'''"); - } - else - { - builder.AppendLine($"'{Capabilities}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Properties), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" properties: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Properties)) - { - if (Properties.Any()) - { - builder.Append(" properties: "); - builder.AppendLine("{"); - foreach (var item in Properties) - { - builder.Append($" '{item.Key}': "); - if (item.Value == null) - { - builder.Append("null"); - continue; - } - if (item.Value.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{item.Value}'''"); - } - else - { - builder.AppendLine($"'{item.Value}'"); - } - } - builder.AppendLine(" }"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ProviderResourceType)} does not support writing '{options.Format}' format."); - } - } - - ProviderResourceType IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeProviderResourceType(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ProviderResourceType)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceType.cs deleted file mode 100644 index 64234b3ba9..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceType.cs +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Resource type managed by the resource provider. - public partial class ProviderResourceType - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ProviderResourceType() - { - Locations = new ChangeTrackingList(); - LocationMappings = new ChangeTrackingList(); - Aliases = new ChangeTrackingList(); - ApiVersions = new ChangeTrackingList(); - ZoneMappings = new ChangeTrackingList(); - ApiProfiles = new ChangeTrackingList(); - Properties = new ChangeTrackingDictionary(); - } - - /// Initializes a new instance of . - /// The resource type. - /// The collection of locations where this resource type can be created. - /// The location mappings that are supported by this resource type. - /// The aliases that are supported by this resource type. - /// The API version. - /// The default API version. - /// - /// The API profiles for the resource provider. - /// The additional capabilities offered by this resource type. - /// The properties. - /// Keeps track of any properties unknown to the library. - internal ProviderResourceType(string resourceType, IReadOnlyList locations, IReadOnlyList locationMappings, IReadOnlyList aliases, IReadOnlyList apiVersions, string defaultApiVersion, IReadOnlyList zoneMappings, IReadOnlyList apiProfiles, string capabilities, IReadOnlyDictionary properties, IDictionary serializedAdditionalRawData) - { - ResourceType = resourceType; - Locations = locations; - LocationMappings = locationMappings; - Aliases = aliases; - ApiVersions = apiVersions; - DefaultApiVersion = defaultApiVersion; - ZoneMappings = zoneMappings; - ApiProfiles = apiProfiles; - Capabilities = capabilities; - Properties = properties; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The resource type. - [WirePath("resourceType")] - public string ResourceType { get; } - /// The collection of locations where this resource type can be created. - [WirePath("locations")] - public IReadOnlyList Locations { get; } - /// The location mappings that are supported by this resource type. - [WirePath("locationMappings")] - public IReadOnlyList LocationMappings { get; } - /// The aliases that are supported by this resource type. - [WirePath("aliases")] - public IReadOnlyList Aliases { get; } - /// The API version. - [WirePath("apiVersions")] - public IReadOnlyList ApiVersions { get; } - /// The default API version. - [WirePath("defaultApiVersion")] - public string DefaultApiVersion { get; } - /// Gets the zone mappings. - [WirePath("zoneMappings")] - public IReadOnlyList ZoneMappings { get; } - /// The API profiles for the resource provider. - [WirePath("apiProfiles")] - public IReadOnlyList ApiProfiles { get; } - /// The additional capabilities offered by this resource type. - [WirePath("capabilities")] - public string Capabilities { get; } - /// The properties. - [WirePath("properties")] - public IReadOnlyDictionary Properties { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceTypeListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceTypeListResult.Serialization.cs deleted file mode 100644 index c8cb061afb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceTypeListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class ProviderResourceTypeListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderResourceTypeListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ProviderResourceTypeListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ProviderResourceTypeListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeProviderResourceTypeListResult(document.RootElement, options); - } - - internal static ProviderResourceTypeListResult DeserializeProviderResourceTypeListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ProviderResourceType.DeserializeProviderResourceType(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ProviderResourceTypeListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ProviderResourceTypeListResult)} does not support writing '{options.Format}' format."); - } - } - - ProviderResourceTypeListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeProviderResourceTypeListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ProviderResourceTypeListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceTypeListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceTypeListResult.cs deleted file mode 100644 index e58854a89d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceTypeListResult.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of resource types of a resource provider. - internal partial class ProviderResourceTypeListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ProviderResourceTypeListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of resource types. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal ProviderResourceTypeListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of resource types. - [WirePath("value")] - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - [WirePath("nextLink")] - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/RegionCategory.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/RegionCategory.cs deleted file mode 100644 index 4f94df158a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/RegionCategory.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The category of the region. - public readonly partial struct RegionCategory : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public RegionCategory(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string RecommendedValue = "Recommended"; - private const string ExtendedValue = "Extended"; - private const string OtherValue = "Other"; - - /// Recommended. - public static RegionCategory Recommended { get; } = new RegionCategory(RecommendedValue); - /// Extended. - public static RegionCategory Extended { get; } = new RegionCategory(ExtendedValue); - /// Other. - public static RegionCategory Other { get; } = new RegionCategory(OtherValue); - /// Determines if two values are the same. - public static bool operator ==(RegionCategory left, RegionCategory right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(RegionCategory left, RegionCategory right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator RegionCategory(string value) => new RegionCategory(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is RegionCategory other && Equals(other); - /// - public bool Equals(RegionCategory other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/RegionType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/RegionType.cs deleted file mode 100644 index b78f1316be..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/RegionType.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The type of the region. - public readonly partial struct RegionType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public RegionType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string PhysicalValue = "Physical"; - private const string LogicalValue = "Logical"; - - /// Physical. - public static RegionType Physical { get; } = new RegionType(PhysicalValue); - /// Logical. - public static RegionType Logical { get; } = new RegionType(LogicalValue); - /// Determines if two values are the same. - public static bool operator ==(RegionType left, RegionType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(RegionType left, RegionType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator RegionType(string value) => new RegionType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is RegionType other && Equals(other); - /// - public bool Equals(RegionType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupExportResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupExportResult.Serialization.cs deleted file mode 100644 index 0c3a290f82..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupExportResult.Serialization.cs +++ /dev/null @@ -1,203 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceGroupExportResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupExportResult)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Template)) - { - writer.WritePropertyName("template"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(Template); -#else - using (JsonDocument document = JsonDocument.Parse(Template, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - if (Optional.IsDefined(Error)) - { - writer.WritePropertyName("error"u8); - JsonSerializer.Serialize(writer, Error); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResourceGroupExportResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupExportResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceGroupExportResult(document.RootElement, options); - } - - internal static ResourceGroupExportResult DeserializeResourceGroupExportResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - BinaryData template = default; - ResponseError error = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("template"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - template = BinaryData.FromString(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("error"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - error = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceGroupExportResult(template, error, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Template), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" template: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Template)) - { - builder.Append(" template: "); - builder.AppendLine($"'{Template.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Error), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" error: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Error)) - { - builder.Append(" error: "); - BicepSerializationHelpers.AppendChildObject(builder, Error, options, 2, false, " error: "); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceGroupExportResult)} does not support writing '{options.Format}' format."); - } - } - - ResourceGroupExportResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceGroupExportResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceGroupExportResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupExportResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupExportResult.cs deleted file mode 100644 index b6a5fd70bd..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupExportResult.cs +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Resource group export result. - public partial class ResourceGroupExportResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceGroupExportResult() - { - } - - /// Initializes a new instance of . - /// The template content. - /// The template export error. - /// Keeps track of any properties unknown to the library. - internal ResourceGroupExportResult(BinaryData template, ResponseError error, IDictionary serializedAdditionalRawData) - { - Template = template; - Error = error; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// - /// The template content. - /// - /// To assign an object to this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("template")] - public BinaryData Template { get; } - /// The template export error. - [WirePath("error")] - public ResponseError Error { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupListResult.Serialization.cs deleted file mode 100644 index 9d18acd599..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class ResourceGroupListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResourceGroupListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceGroupListResult(document.RootElement, options); - } - - internal static ResourceGroupListResult DeserializeResourceGroupListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ResourceGroupData.DeserializeResourceGroupData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceGroupListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceGroupListResult)} does not support writing '{options.Format}' format."); - } - } - - ResourceGroupListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceGroupListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceGroupListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupListResult.cs deleted file mode 100644 index aad563b999..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of resource groups. - internal partial class ResourceGroupListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceGroupListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of resource groups. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal ResourceGroupListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of resource groups. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupPatch.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupPatch.Serialization.cs deleted file mode 100644 index 37de7fd731..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupPatch.Serialization.cs +++ /dev/null @@ -1,181 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceGroupPatch : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupPatch)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(Properties)) - { - writer.WritePropertyName("properties"u8); - writer.WriteObjectValue(Properties, options); - } - if (Optional.IsDefined(ManagedBy)) - { - writer.WritePropertyName("managedBy"u8); - writer.WriteStringValue(ManagedBy); - } - if (Optional.IsCollectionDefined(Tags)) - { - writer.WritePropertyName("tags"u8); - writer.WriteStartObject(); - foreach (var item in Tags) - { - writer.WritePropertyName(item.Key); - writer.WriteStringValue(item.Value); - } - writer.WriteEndObject(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResourceGroupPatch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupPatch)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceGroupPatch(document.RootElement, options); - } - - internal static ResourceGroupPatch DeserializeResourceGroupPatch(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - ResourceGroupProperties properties = default; - string managedBy = default; - IDictionary tags = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - properties = ResourceGroupProperties.DeserializeResourceGroupProperties(property.Value, options); - continue; - } - if (property.NameEquals("managedBy"u8)) - { - managedBy = property.Value.GetString(); - continue; - } - if (property.NameEquals("tags"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - tags = dictionary; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceGroupPatch(name, properties, managedBy, tags ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ResourceGroupPatch)} does not support writing '{options.Format}' format."); - } - } - - ResourceGroupPatch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceGroupPatch(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceGroupPatch)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupPatch.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupPatch.cs deleted file mode 100644 index b10e558b03..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupPatch.cs +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Resource group information. - public partial class ResourceGroupPatch - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ResourceGroupPatch() - { - Tags = new ChangeTrackingDictionary(); - } - - /// Initializes a new instance of . - /// The name of the resource group. - /// The resource group properties. - /// The ID of the resource that manages this resource group. - /// The tags attached to the resource group. - /// Keeps track of any properties unknown to the library. - internal ResourceGroupPatch(string name, ResourceGroupProperties properties, string managedBy, IDictionary tags, IDictionary serializedAdditionalRawData) - { - Name = name; - Properties = properties; - ManagedBy = managedBy; - Tags = tags; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The name of the resource group. - [WirePath("name")] - public string Name { get; set; } - /// The resource group properties. - internal ResourceGroupProperties Properties { get; set; } - /// The provisioning state. - [WirePath("properties.provisioningState")] - public string ResourceGroupProvisioningState - { - get => Properties is null ? default : Properties.ProvisioningState; - } - - /// The ID of the resource that manages this resource group. - [WirePath("managedBy")] - public string ManagedBy { get; set; } - /// The tags attached to the resource group. - [WirePath("tags")] - public IDictionary Tags { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupProperties.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupProperties.Serialization.cs deleted file mode 100644 index 4ecf59e702..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupProperties.Serialization.cs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class ResourceGroupProperties : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupProperties)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(ProvisioningState)) - { - writer.WritePropertyName("provisioningState"u8); - writer.WriteStringValue(ProvisioningState); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResourceGroupProperties IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupProperties)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceGroupProperties(document.RootElement, options); - } - - internal static ResourceGroupProperties DeserializeResourceGroupProperties(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string provisioningState = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("provisioningState"u8)) - { - provisioningState = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceGroupProperties(provisioningState, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ProvisioningState), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" provisioningState: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ProvisioningState)) - { - builder.Append(" provisioningState: "); - if (ProvisioningState.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ProvisioningState}'''"); - } - else - { - builder.AppendLine($"'{ProvisioningState}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceGroupProperties)} does not support writing '{options.Format}' format."); - } - } - - ResourceGroupProperties IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceGroupProperties(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceGroupProperties)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupProperties.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupProperties.cs deleted file mode 100644 index b62fad0a7f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupProperties.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The resource group properties. - internal partial class ResourceGroupProperties - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ResourceGroupProperties() - { - } - - /// Initializes a new instance of . - /// The provisioning state. - /// Keeps track of any properties unknown to the library. - internal ResourceGroupProperties(string provisioningState, IDictionary serializedAdditionalRawData) - { - ProvisioningState = provisioningState; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The provisioning state. - [WirePath("provisioningState")] - public string ProvisioningState { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceListResult.Serialization.cs deleted file mode 100644 index f5e92f7eaa..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class ResourceListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResourceListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceListResult(document.RootElement, options); - } - - internal static ResourceListResult DeserializeResourceListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(GenericResourceData.DeserializeGenericResourceData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceListResult)} does not support writing '{options.Format}' format."); - } - } - - ResourceListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceListResult.cs deleted file mode 100644 index 6d1d19e150..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of resource groups. - internal partial class ResourceListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of resources. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal ResourceListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of resources. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationContent.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationContent.Serialization.cs deleted file mode 100644 index 1ea0840131..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationContent.Serialization.cs +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceNameValidationContent : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceNameValidationContent)} does not support writing '{format}' format."); - } - - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ResourceType); - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResourceNameValidationContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceNameValidationContent)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceNameValidationContent(document.RootElement, options); - } - - internal static ResourceNameValidationContent DeserializeResourceNameValidationContent(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - ResourceType type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceNameValidationContent(name, type, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ResourceNameValidationContent)} does not support writing '{options.Format}' format."); - } - } - - ResourceNameValidationContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceNameValidationContent(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceNameValidationContent)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationContent.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationContent.cs deleted file mode 100644 index e3886a6c2f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationContent.cs +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Name and Type of the Resource. - public partial class ResourceNameValidationContent - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// Name of the resource. - /// The type of the resource. - /// is null. - public ResourceNameValidationContent(string name, ResourceType resourceType) - { - Argument.AssertNotNull(name, nameof(name)); - - Name = name; - ResourceType = resourceType; - } - - /// Initializes a new instance of . - /// Name of the resource. - /// The type of the resource. - /// Keeps track of any properties unknown to the library. - internal ResourceNameValidationContent(string name, ResourceType resourceType, IDictionary serializedAdditionalRawData) - { - Name = name; - ResourceType = resourceType; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal ResourceNameValidationContent() - { - } - - /// Name of the resource. - [WirePath("name")] - public string Name { get; } - /// The type of the resource. - [WirePath("type")] - public ResourceType ResourceType { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationResult.Serialization.cs deleted file mode 100644 index 46ee78b1e3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationResult.Serialization.cs +++ /dev/null @@ -1,230 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceNameValidationResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceNameValidationResult)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(ResourceType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(ResourceType.Value); - } - if (Optional.IsDefined(Status)) - { - writer.WritePropertyName("status"u8); - writer.WriteStringValue(Status.Value.ToString()); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResourceNameValidationResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceNameValidationResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceNameValidationResult(document.RootElement, options); - } - - internal static ResourceNameValidationResult DeserializeResourceNameValidationResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - ResourceType? type = default; - ResourceNameValidationStatus? status = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("status"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - status = new ResourceNameValidationStatus(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceNameValidationResult(name, type, status, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ResourceType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" type: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ResourceType)) - { - builder.Append(" type: "); - builder.AppendLine($"'{ResourceType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Status), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" status: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Status)) - { - builder.Append(" status: "); - builder.AppendLine($"'{Status.Value.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceNameValidationResult)} does not support writing '{options.Format}' format."); - } - } - - ResourceNameValidationResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceNameValidationResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceNameValidationResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationResult.cs deleted file mode 100644 index 7e0501f862..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationResult.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Resource Name valid if not a reserved word, does not contain a reserved word and does not start with a reserved word. - public partial class ResourceNameValidationResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceNameValidationResult() - { - } - - /// Initializes a new instance of . - /// Name of Resource. - /// Type of Resource. - /// Is the resource name Allowed or Reserved. - /// Keeps track of any properties unknown to the library. - internal ResourceNameValidationResult(string name, ResourceType? resourceType, ResourceNameValidationStatus? status, IDictionary serializedAdditionalRawData) - { - Name = name; - ResourceType = resourceType; - Status = status; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Name of Resource. - [WirePath("name")] - public string Name { get; } - /// Type of Resource. - [WirePath("type")] - public ResourceType? ResourceType { get; } - /// Is the resource name Allowed or Reserved. - [WirePath("status")] - public ResourceNameValidationStatus? Status { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationStatus.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationStatus.cs deleted file mode 100644 index 78a1b378f1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationStatus.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Is the resource name Allowed or Reserved. - public readonly partial struct ResourceNameValidationStatus : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ResourceNameValidationStatus(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string AllowedValue = "Allowed"; - private const string ReservedValue = "Reserved"; - - /// Allowed. - public static ResourceNameValidationStatus Allowed { get; } = new ResourceNameValidationStatus(AllowedValue); - /// Reserved. - public static ResourceNameValidationStatus Reserved { get; } = new ResourceNameValidationStatus(ReservedValue); - /// Determines if two values are the same. - public static bool operator ==(ResourceNameValidationStatus left, ResourceNameValidationStatus right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ResourceNameValidationStatus left, ResourceNameValidationStatus right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ResourceNameValidationStatus(string value) => new ResourceNameValidationStatus(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ResourceNameValidationStatus other && Equals(other); - /// - public bool Equals(ResourceNameValidationStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceProviderListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceProviderListResult.Serialization.cs deleted file mode 100644 index e8668c7885..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceProviderListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class ResourceProviderListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceProviderListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResourceProviderListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceProviderListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceProviderListResult(document.RootElement, options); - } - - internal static ResourceProviderListResult DeserializeResourceProviderListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ResourceProviderData.DeserializeResourceProviderData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceProviderListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceProviderListResult)} does not support writing '{options.Format}' format."); - } - } - - ResourceProviderListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceProviderListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceProviderListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceProviderListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceProviderListResult.cs deleted file mode 100644 index 1049d3073b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceProviderListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of resource providers. - internal partial class ResourceProviderListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceProviderListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of resource providers. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal ResourceProviderListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of resource providers. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelector.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelector.Serialization.cs deleted file mode 100644 index 68ac0784f5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelector.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceSelector : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceSelector)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsCollectionDefined(Selectors)) - { - writer.WritePropertyName("selectors"u8); - writer.WriteStartArray(); - foreach (var item in Selectors) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResourceSelector IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceSelector)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceSelector(document.RootElement, options); - } - - internal static ResourceSelector DeserializeResourceSelector(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - IList selectors = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("selectors"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ResourceSelectorExpression.DeserializeResourceSelectorExpression(item, options)); - } - selectors = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceSelector(name, selectors ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Selectors), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" selectors: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Selectors)) - { - if (Selectors.Any()) - { - builder.Append(" selectors: "); - builder.AppendLine("["); - foreach (var item in Selectors) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " selectors: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceSelector)} does not support writing '{options.Format}' format."); - } - } - - ResourceSelector IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceSelector(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceSelector)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelector.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelector.cs deleted file mode 100644 index e85c7541cb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelector.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The resource selector to filter policies by resource properties. - public partial class ResourceSelector - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ResourceSelector() - { - Selectors = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The name of the resource selector. - /// The list of the selector expressions. - /// Keeps track of any properties unknown to the library. - internal ResourceSelector(string name, IList selectors, IDictionary serializedAdditionalRawData) - { - Name = name; - Selectors = selectors; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The name of the resource selector. - [WirePath("name")] - public string Name { get; set; } - /// The list of the selector expressions. - [WirePath("selectors")] - public IList Selectors { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorExpression.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorExpression.Serialization.cs deleted file mode 100644 index 78c6046176..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorExpression.Serialization.cs +++ /dev/null @@ -1,289 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceSelectorExpression : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceSelectorExpression)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Kind)) - { - writer.WritePropertyName("kind"u8); - writer.WriteStringValue(Kind.Value.ToString()); - } - if (Optional.IsCollectionDefined(In)) - { - writer.WritePropertyName("in"u8); - writer.WriteStartArray(); - foreach (var item in In) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(NotIn)) - { - writer.WritePropertyName("notIn"u8); - writer.WriteStartArray(); - foreach (var item in NotIn) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResourceSelectorExpression IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceSelectorExpression)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceSelectorExpression(document.RootElement, options); - } - - internal static ResourceSelectorExpression DeserializeResourceSelectorExpression(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceSelectorKind? kind = default; - IList @in = default; - IList notIn = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("kind"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - kind = new ResourceSelectorKind(property.Value.GetString()); - continue; - } - if (property.NameEquals("in"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - @in = array; - continue; - } - if (property.NameEquals("notIn"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - notIn = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceSelectorExpression(kind, @in ?? new ChangeTrackingList(), notIn ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Kind), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" kind: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Kind)) - { - builder.Append(" kind: "); - builder.AppendLine($"'{Kind.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(In), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" in: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(In)) - { - if (In.Any()) - { - builder.Append(" in: "); - builder.AppendLine("["); - foreach (var item in In) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NotIn), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" notIn: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(NotIn)) - { - if (NotIn.Any()) - { - builder.Append(" notIn: "); - builder.AppendLine("["); - foreach (var item in NotIn) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceSelectorExpression)} does not support writing '{options.Format}' format."); - } - } - - ResourceSelectorExpression IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceSelectorExpression(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceSelectorExpression)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorExpression.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorExpression.cs deleted file mode 100644 index c10dad80a6..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorExpression.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The selector expression. - public partial class ResourceSelectorExpression - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ResourceSelectorExpression() - { - In = new ChangeTrackingList(); - NotIn = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The selector kind. - /// The list of values to filter in. - /// The list of values to filter out. - /// Keeps track of any properties unknown to the library. - internal ResourceSelectorExpression(ResourceSelectorKind? kind, IList @in, IList notIn, IDictionary serializedAdditionalRawData) - { - Kind = kind; - In = @in; - NotIn = notIn; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The selector kind. - [WirePath("kind")] - public ResourceSelectorKind? Kind { get; set; } - /// The list of values to filter in. - [WirePath("in")] - public IList In { get; } - /// The list of values to filter out. - [WirePath("notIn")] - public IList NotIn { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorKind.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorKind.cs deleted file mode 100644 index bed65e9a77..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorKind.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The selector kind. - public readonly partial struct ResourceSelectorKind : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ResourceSelectorKind(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string ResourceLocationValue = "resourceLocation"; - private const string ResourceTypeValue = "resourceType"; - private const string ResourceWithoutLocationValue = "resourceWithoutLocation"; - private const string PolicyDefinitionReferenceIdValue = "policyDefinitionReferenceId"; - - /// The selector kind to filter policies by the resource location. - public static ResourceSelectorKind ResourceLocation { get; } = new ResourceSelectorKind(ResourceLocationValue); - /// The selector kind to filter policies by the resource type. - public static ResourceSelectorKind ResourceType { get; } = new ResourceSelectorKind(ResourceTypeValue); - /// The selector kind to filter policies by the resource without location. - public static ResourceSelectorKind ResourceWithoutLocation { get; } = new ResourceSelectorKind(ResourceWithoutLocationValue); - /// The selector kind to filter policies by the policy definition reference ID. - public static ResourceSelectorKind PolicyDefinitionReferenceId { get; } = new ResourceSelectorKind(PolicyDefinitionReferenceIdValue); - /// Determines if two values are the same. - public static bool operator ==(ResourceSelectorKind left, ResourceSelectorKind right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ResourceSelectorKind left, ResourceSelectorKind right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ResourceSelectorKind(string value) => new ResourceSelectorKind(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ResourceSelectorKind other && Equals(other); - /// - public bool Equals(ResourceSelectorKind other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAlias.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAlias.Serialization.cs deleted file mode 100644 index 6e05a2234c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAlias.Serialization.cs +++ /dev/null @@ -1,350 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceTypeAlias : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAlias)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsCollectionDefined(Paths)) - { - writer.WritePropertyName("paths"u8); - writer.WriteStartArray(); - foreach (var item in Paths) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(AliasType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(AliasType.Value.ToSerialString()); - } - if (Optional.IsDefined(DefaultPath)) - { - writer.WritePropertyName("defaultPath"u8); - writer.WriteStringValue(DefaultPath); - } - if (Optional.IsDefined(DefaultPattern)) - { - writer.WritePropertyName("defaultPattern"u8); - writer.WriteObjectValue(DefaultPattern, options); - } - if (options.Format != "W" && Optional.IsDefined(DefaultMetadata)) - { - writer.WritePropertyName("defaultMetadata"u8); - writer.WriteObjectValue(DefaultMetadata, options); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResourceTypeAlias IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAlias)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceTypeAlias(document.RootElement, options); - } - - internal static ResourceTypeAlias DeserializeResourceTypeAlias(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - IReadOnlyList paths = default; - ResourceTypeAliasType? type = default; - string defaultPath = default; - ResourceTypeAliasPattern defaultPattern = default; - ResourceTypeAliasPathMetadata defaultMetadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("paths"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ResourceTypeAliasPath.DeserializeResourceTypeAliasPath(item, options)); - } - paths = array; - continue; - } - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = property.Value.GetString().ToResourceTypeAliasType(); - continue; - } - if (property.NameEquals("defaultPath"u8)) - { - defaultPath = property.Value.GetString(); - continue; - } - if (property.NameEquals("defaultPattern"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - defaultPattern = ResourceTypeAliasPattern.DeserializeResourceTypeAliasPattern(property.Value, options); - continue; - } - if (property.NameEquals("defaultMetadata"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - defaultMetadata = ResourceTypeAliasPathMetadata.DeserializeResourceTypeAliasPathMetadata(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceTypeAlias( - name, - paths ?? new ChangeTrackingList(), - type, - defaultPath, - defaultPattern, - defaultMetadata, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Paths), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" paths: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Paths)) - { - if (Paths.Any()) - { - builder.Append(" paths: "); - builder.AppendLine("["); - foreach (var item in Paths) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " paths: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(AliasType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" type: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(AliasType)) - { - builder.Append(" type: "); - builder.AppendLine($"'{AliasType.Value.ToSerialString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DefaultPath), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" defaultPath: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DefaultPath)) - { - builder.Append(" defaultPath: "); - if (DefaultPath.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DefaultPath}'''"); - } - else - { - builder.AppendLine($"'{DefaultPath}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DefaultPattern), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" defaultPattern: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DefaultPattern)) - { - builder.Append(" defaultPattern: "); - BicepSerializationHelpers.AppendChildObject(builder, DefaultPattern, options, 2, false, " defaultPattern: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DefaultMetadata), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" defaultMetadata: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DefaultMetadata)) - { - builder.Append(" defaultMetadata: "); - BicepSerializationHelpers.AppendChildObject(builder, DefaultMetadata, options, 2, false, " defaultMetadata: "); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceTypeAlias)} does not support writing '{options.Format}' format."); - } - } - - ResourceTypeAlias IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceTypeAlias(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceTypeAlias)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAlias.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAlias.cs deleted file mode 100644 index 26ac43a913..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAlias.cs +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The alias type. - public partial class ResourceTypeAlias - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceTypeAlias() - { - Paths = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The alias name. - /// The paths for an alias. - /// The type of the alias. - /// The default path for an alias. - /// The default pattern for an alias. - /// The default alias path metadata. Applies to the default path and to any alias path that doesn't have metadata. - /// Keeps track of any properties unknown to the library. - internal ResourceTypeAlias(string name, IReadOnlyList paths, ResourceTypeAliasType? aliasType, string defaultPath, ResourceTypeAliasPattern defaultPattern, ResourceTypeAliasPathMetadata defaultMetadata, IDictionary serializedAdditionalRawData) - { - Name = name; - Paths = paths; - AliasType = aliasType; - DefaultPath = defaultPath; - DefaultPattern = defaultPattern; - DefaultMetadata = defaultMetadata; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The alias name. - [WirePath("name")] - public string Name { get; } - /// The paths for an alias. - [WirePath("paths")] - public IReadOnlyList Paths { get; } - /// The type of the alias. - [WirePath("type")] - public ResourceTypeAliasType? AliasType { get; } - /// The default path for an alias. - [WirePath("defaultPath")] - public string DefaultPath { get; } - /// The default pattern for an alias. - [WirePath("defaultPattern")] - public ResourceTypeAliasPattern DefaultPattern { get; } - /// The default alias path metadata. Applies to the default path and to any alias path that doesn't have metadata. - [WirePath("defaultMetadata")] - public ResourceTypeAliasPathMetadata DefaultMetadata { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPath.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPath.Serialization.cs deleted file mode 100644 index bf32500a35..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPath.Serialization.cs +++ /dev/null @@ -1,292 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceTypeAliasPath : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAliasPath)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Path)) - { - writer.WritePropertyName("path"u8); - writer.WriteStringValue(Path); - } - if (Optional.IsCollectionDefined(ApiVersions)) - { - writer.WritePropertyName("apiVersions"u8); - writer.WriteStartArray(); - foreach (var item in ApiVersions) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(Pattern)) - { - writer.WritePropertyName("pattern"u8); - writer.WriteObjectValue(Pattern, options); - } - if (options.Format != "W" && Optional.IsDefined(Metadata)) - { - writer.WritePropertyName("metadata"u8); - writer.WriteObjectValue(Metadata, options); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResourceTypeAliasPath IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAliasPath)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceTypeAliasPath(document.RootElement, options); - } - - internal static ResourceTypeAliasPath DeserializeResourceTypeAliasPath(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string path = default; - IReadOnlyList apiVersions = default; - ResourceTypeAliasPattern pattern = default; - ResourceTypeAliasPathMetadata metadata = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("path"u8)) - { - path = property.Value.GetString(); - continue; - } - if (property.NameEquals("apiVersions"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - apiVersions = array; - continue; - } - if (property.NameEquals("pattern"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - pattern = ResourceTypeAliasPattern.DeserializeResourceTypeAliasPattern(property.Value, options); - continue; - } - if (property.NameEquals("metadata"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - metadata = ResourceTypeAliasPathMetadata.DeserializeResourceTypeAliasPathMetadata(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceTypeAliasPath(path, apiVersions ?? new ChangeTrackingList(), pattern, metadata, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Path), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" path: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Path)) - { - builder.Append(" path: "); - if (Path.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Path}'''"); - } - else - { - builder.AppendLine($"'{Path}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ApiVersions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" apiVersions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ApiVersions)) - { - if (ApiVersions.Any()) - { - builder.Append(" apiVersions: "); - builder.AppendLine("["); - foreach (var item in ApiVersions) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Pattern), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" pattern: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Pattern)) - { - builder.Append(" pattern: "); - BicepSerializationHelpers.AppendChildObject(builder, Pattern, options, 2, false, " pattern: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Metadata), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" metadata: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Metadata)) - { - builder.Append(" metadata: "); - BicepSerializationHelpers.AppendChildObject(builder, Metadata, options, 2, false, " metadata: "); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceTypeAliasPath)} does not support writing '{options.Format}' format."); - } - } - - ResourceTypeAliasPath IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceTypeAliasPath(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceTypeAliasPath)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPath.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPath.cs deleted file mode 100644 index acd74e09e7..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPath.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The type of the paths for alias. - public partial class ResourceTypeAliasPath - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceTypeAliasPath() - { - ApiVersions = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The path of an alias. - /// The API versions. - /// The pattern for an alias path. - /// The metadata of the alias path. If missing, fall back to the default metadata of the alias. - /// Keeps track of any properties unknown to the library. - internal ResourceTypeAliasPath(string path, IReadOnlyList apiVersions, ResourceTypeAliasPattern pattern, ResourceTypeAliasPathMetadata metadata, IDictionary serializedAdditionalRawData) - { - Path = path; - ApiVersions = apiVersions; - Pattern = pattern; - Metadata = metadata; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The path of an alias. - [WirePath("path")] - public string Path { get; } - /// The API versions. - [WirePath("apiVersions")] - public IReadOnlyList ApiVersions { get; } - /// The pattern for an alias path. - [WirePath("pattern")] - public ResourceTypeAliasPattern Pattern { get; } - /// The metadata of the alias path. If missing, fall back to the default metadata of the alias. - [WirePath("metadata")] - public ResourceTypeAliasPathMetadata Metadata { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathAttributes.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathAttributes.cs deleted file mode 100644 index 217d95e60d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathAttributes.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The attributes of the token that the alias path is referring to. - public readonly partial struct ResourceTypeAliasPathAttributes : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ResourceTypeAliasPathAttributes(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string NoneValue = "None"; - private const string ModifiableValue = "Modifiable"; - - /// The token that the alias path is referring to has no attributes. - public static ResourceTypeAliasPathAttributes None { get; } = new ResourceTypeAliasPathAttributes(NoneValue); - /// The token that the alias path is referring to is modifiable by policies with 'modify' effect. - public static ResourceTypeAliasPathAttributes Modifiable { get; } = new ResourceTypeAliasPathAttributes(ModifiableValue); - /// Determines if two values are the same. - public static bool operator ==(ResourceTypeAliasPathAttributes left, ResourceTypeAliasPathAttributes right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ResourceTypeAliasPathAttributes left, ResourceTypeAliasPathAttributes right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ResourceTypeAliasPathAttributes(string value) => new ResourceTypeAliasPathAttributes(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ResourceTypeAliasPathAttributes other && Equals(other); - /// - public bool Equals(ResourceTypeAliasPathAttributes other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathMetadata.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathMetadata.Serialization.cs deleted file mode 100644 index a4f23ac02b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathMetadata.Serialization.cs +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceTypeAliasPathMetadata : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAliasPathMetadata)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(TokenType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(TokenType.Value.ToString()); - } - if (options.Format != "W" && Optional.IsDefined(Attributes)) - { - writer.WritePropertyName("attributes"u8); - writer.WriteStringValue(Attributes.Value.ToString()); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResourceTypeAliasPathMetadata IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAliasPathMetadata)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceTypeAliasPathMetadata(document.RootElement, options); - } - - internal static ResourceTypeAliasPathMetadata DeserializeResourceTypeAliasPathMetadata(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceTypeAliasPathTokenType? type = default; - ResourceTypeAliasPathAttributes? attributes = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = new ResourceTypeAliasPathTokenType(property.Value.GetString()); - continue; - } - if (property.NameEquals("attributes"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - attributes = new ResourceTypeAliasPathAttributes(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceTypeAliasPathMetadata(type, attributes, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TokenType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" type: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TokenType)) - { - builder.Append(" type: "); - builder.AppendLine($"'{TokenType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Attributes), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" attributes: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Attributes)) - { - builder.Append(" attributes: "); - builder.AppendLine($"'{Attributes.Value.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceTypeAliasPathMetadata)} does not support writing '{options.Format}' format."); - } - } - - ResourceTypeAliasPathMetadata IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceTypeAliasPathMetadata(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceTypeAliasPathMetadata)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathMetadata.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathMetadata.cs deleted file mode 100644 index 1a4b48937b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathMetadata.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The ResourceTypeAliasPathMetadata. - public partial class ResourceTypeAliasPathMetadata - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceTypeAliasPathMetadata() - { - } - - /// Initializes a new instance of . - /// The type of the token that the alias path is referring to. - /// The attributes of the token that the alias path is referring to. - /// Keeps track of any properties unknown to the library. - internal ResourceTypeAliasPathMetadata(ResourceTypeAliasPathTokenType? tokenType, ResourceTypeAliasPathAttributes? attributes, IDictionary serializedAdditionalRawData) - { - TokenType = tokenType; - Attributes = attributes; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The type of the token that the alias path is referring to. - [WirePath("type")] - public ResourceTypeAliasPathTokenType? TokenType { get; } - /// The attributes of the token that the alias path is referring to. - [WirePath("attributes")] - public ResourceTypeAliasPathAttributes? Attributes { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathTokenType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathTokenType.cs deleted file mode 100644 index 98fd72b001..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathTokenType.cs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The type of the token that the alias path is referring to. - public readonly partial struct ResourceTypeAliasPathTokenType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ResourceTypeAliasPathTokenType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string NotSpecifiedValue = "NotSpecified"; - private const string AnyValue = "Any"; - private const string StringValue = "String"; - private const string ObjectValue = "Object"; - private const string ArrayValue = "Array"; - private const string IntegerValue = "Integer"; - private const string NumberValue = "Number"; - private const string BooleanValue = "Boolean"; - - /// The token type is not specified. - public static ResourceTypeAliasPathTokenType NotSpecified { get; } = new ResourceTypeAliasPathTokenType(NotSpecifiedValue); - /// The token type can be anything. - public static ResourceTypeAliasPathTokenType Any { get; } = new ResourceTypeAliasPathTokenType(AnyValue); - /// The token type is string. - public static ResourceTypeAliasPathTokenType String { get; } = new ResourceTypeAliasPathTokenType(StringValue); - /// The token type is object. - public static ResourceTypeAliasPathTokenType Object { get; } = new ResourceTypeAliasPathTokenType(ObjectValue); - /// The token type is array. - public static ResourceTypeAliasPathTokenType Array { get; } = new ResourceTypeAliasPathTokenType(ArrayValue); - /// The token type is integer. - public static ResourceTypeAliasPathTokenType Integer { get; } = new ResourceTypeAliasPathTokenType(IntegerValue); - /// The token type is number. - public static ResourceTypeAliasPathTokenType Number { get; } = new ResourceTypeAliasPathTokenType(NumberValue); - /// The token type is boolean. - public static ResourceTypeAliasPathTokenType Boolean { get; } = new ResourceTypeAliasPathTokenType(BooleanValue); - /// Determines if two values are the same. - public static bool operator ==(ResourceTypeAliasPathTokenType left, ResourceTypeAliasPathTokenType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ResourceTypeAliasPathTokenType left, ResourceTypeAliasPathTokenType right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator ResourceTypeAliasPathTokenType(string value) => new ResourceTypeAliasPathTokenType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ResourceTypeAliasPathTokenType other && Equals(other); - /// - public bool Equals(ResourceTypeAliasPathTokenType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPattern.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPattern.Serialization.cs deleted file mode 100644 index ed9f763b2d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPattern.Serialization.cs +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceTypeAliasPattern : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAliasPattern)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Phrase)) - { - writer.WritePropertyName("phrase"u8); - writer.WriteStringValue(Phrase); - } - if (Optional.IsDefined(Variable)) - { - writer.WritePropertyName("variable"u8); - writer.WriteStringValue(Variable); - } - if (Optional.IsDefined(PatternType)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(PatternType.Value.ToSerialString()); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResourceTypeAliasPattern IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAliasPattern)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceTypeAliasPattern(document.RootElement, options); - } - - internal static ResourceTypeAliasPattern DeserializeResourceTypeAliasPattern(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string phrase = default; - string variable = default; - ResourceTypeAliasPatternType? type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("phrase"u8)) - { - phrase = property.Value.GetString(); - continue; - } - if (property.NameEquals("variable"u8)) - { - variable = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - type = property.Value.GetString().ToResourceTypeAliasPatternType(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceTypeAliasPattern(phrase, variable, type, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Phrase), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" phrase: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Phrase)) - { - builder.Append(" phrase: "); - if (Phrase.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Phrase}'''"); - } - else - { - builder.AppendLine($"'{Phrase}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Variable), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" variable: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Variable)) - { - builder.Append(" variable: "); - if (Variable.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Variable}'''"); - } - else - { - builder.AppendLine($"'{Variable}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PatternType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" type: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PatternType)) - { - builder.Append(" type: "); - builder.AppendLine($"'{PatternType.Value.ToSerialString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceTypeAliasPattern)} does not support writing '{options.Format}' format."); - } - } - - ResourceTypeAliasPattern IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceTypeAliasPattern(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceTypeAliasPattern)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPattern.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPattern.cs deleted file mode 100644 index 5c318a2dde..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPattern.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The type of the pattern for an alias path. - public partial class ResourceTypeAliasPattern - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceTypeAliasPattern() - { - } - - /// Initializes a new instance of . - /// The alias pattern phrase. - /// The alias pattern variable. - /// The type of alias pattern. - /// Keeps track of any properties unknown to the library. - internal ResourceTypeAliasPattern(string phrase, string variable, ResourceTypeAliasPatternType? patternType, IDictionary serializedAdditionalRawData) - { - Phrase = phrase; - Variable = variable; - PatternType = patternType; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The alias pattern phrase. - [WirePath("phrase")] - public string Phrase { get; } - /// The alias pattern variable. - [WirePath("variable")] - public string Variable { get; } - /// The type of alias pattern. - [WirePath("type")] - public ResourceTypeAliasPatternType? PatternType { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPatternType.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPatternType.Serialization.cs deleted file mode 100644 index 8faaf01391..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPatternType.Serialization.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.Resources.Models -{ - internal static partial class ResourceTypeAliasPatternTypeExtensions - { - public static string ToSerialString(this ResourceTypeAliasPatternType value) => value switch - { - ResourceTypeAliasPatternType.NotSpecified => "NotSpecified", - ResourceTypeAliasPatternType.Extract => "Extract", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ResourceTypeAliasPatternType value.") - }; - - public static ResourceTypeAliasPatternType ToResourceTypeAliasPatternType(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "NotSpecified")) return ResourceTypeAliasPatternType.NotSpecified; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Extract")) return ResourceTypeAliasPatternType.Extract; - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ResourceTypeAliasPatternType value."); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPatternType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPatternType.cs deleted file mode 100644 index 8ed0430db1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPatternType.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.Resources.Models -{ - /// The type of alias pattern. - public enum ResourceTypeAliasPatternType - { - /// NotSpecified is not allowed. - NotSpecified, - /// Extract is the only allowed value. - Extract - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasType.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasType.Serialization.cs deleted file mode 100644 index 2ddd82d437..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasType.Serialization.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.Resources.Models -{ - internal static partial class ResourceTypeAliasTypeExtensions - { - public static string ToSerialString(this ResourceTypeAliasType value) => value switch - { - ResourceTypeAliasType.NotSpecified => "NotSpecified", - ResourceTypeAliasType.PlainText => "PlainText", - ResourceTypeAliasType.Mask => "Mask", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ResourceTypeAliasType value.") - }; - - public static ResourceTypeAliasType ToResourceTypeAliasType(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "NotSpecified")) return ResourceTypeAliasType.NotSpecified; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "PlainText")) return ResourceTypeAliasType.PlainText; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Mask")) return ResourceTypeAliasType.Mask; - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ResourceTypeAliasType value."); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasType.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasType.cs deleted file mode 100644 index b111828d70..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasType.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.Resources.Models -{ - /// The type of the alias. - public enum ResourceTypeAliasType - { - /// Alias type is unknown (same as not providing alias type). - NotSpecified, - /// Alias value is not secret. - PlainText, - /// Alias value is secret. - Mask - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliases.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliases.Serialization.cs deleted file mode 100644 index 96f55ab14c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliases.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourceTypeAliases : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAliases)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(ResourceType)) - { - writer.WritePropertyName("resourceType"u8); - writer.WriteStringValue(ResourceType); - } - if (Optional.IsCollectionDefined(Aliases)) - { - writer.WritePropertyName("aliases"u8); - writer.WriteStartArray(); - foreach (var item in Aliases) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResourceTypeAliases IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceTypeAliases)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceTypeAliases(document.RootElement, options); - } - - internal static ResourceTypeAliases DeserializeResourceTypeAliases(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string resourceType = default; - IReadOnlyList aliases = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("resourceType"u8)) - { - resourceType = property.Value.GetString(); - continue; - } - if (property.NameEquals("aliases"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ResourceTypeAlias.DeserializeResourceTypeAlias(item, options)); - } - aliases = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceTypeAliases(resourceType, aliases ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ResourceType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" resourceType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ResourceType)) - { - builder.Append(" resourceType: "); - if (ResourceType.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ResourceType}'''"); - } - else - { - builder.AppendLine($"'{ResourceType}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Aliases), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" aliases: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Aliases)) - { - if (Aliases.Any()) - { - builder.Append(" aliases: "); - builder.AppendLine("["); - foreach (var item in Aliases) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " aliases: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceTypeAliases)} does not support writing '{options.Format}' format."); - } - } - - ResourceTypeAliases IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceTypeAliases(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceTypeAliases)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliases.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliases.cs deleted file mode 100644 index 872c369df5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliases.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The resource type aliases definition. - public partial class ResourceTypeAliases - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ResourceTypeAliases() - { - Aliases = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The resource type name. - /// The aliases for property names. - /// Keeps track of any properties unknown to the library. - internal ResourceTypeAliases(string resourceType, IReadOnlyList aliases, IDictionary serializedAdditionalRawData) - { - ResourceType = resourceType; - Aliases = aliases; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The resource type name. - [WirePath("resourceType")] - public string ResourceType { get; } - /// The aliases for property names. - [WirePath("aliases")] - public IReadOnlyList Aliases { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesMoveContent.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesMoveContent.Serialization.cs deleted file mode 100644 index 88cd1fb383..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesMoveContent.Serialization.cs +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourcesMoveContent : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourcesMoveContent)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Resources)) - { - writer.WritePropertyName("resources"u8); - writer.WriteStartArray(); - foreach (var item in Resources) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(TargetResourceGroupId)) - { - writer.WritePropertyName("targetResourceGroup"u8); - writer.WriteStringValue(TargetResourceGroupId); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResourcesMoveContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourcesMoveContent)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourcesMoveContent(document.RootElement, options); - } - - internal static ResourcesMoveContent DeserializeResourcesMoveContent(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IList resources = default; - ResourceIdentifier targetResourceGroup = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("resources"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - resources = array; - continue; - } - if (property.NameEquals("targetResourceGroup"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - targetResourceGroup = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourcesMoveContent(resources ?? new ChangeTrackingList(), targetResourceGroup, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(ResourcesMoveContent)} does not support writing '{options.Format}' format."); - } - } - - ResourcesMoveContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourcesMoveContent(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourcesMoveContent)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesMoveContent.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesMoveContent.cs deleted file mode 100644 index 89139c1b2e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesMoveContent.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Parameters of move resources. - public partial class ResourcesMoveContent - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ResourcesMoveContent() - { - Resources = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The IDs of the resources. - /// The target resource group. - /// Keeps track of any properties unknown to the library. - internal ResourcesMoveContent(IList resources, ResourceIdentifier targetResourceGroupId, IDictionary serializedAdditionalRawData) - { - Resources = resources; - TargetResourceGroupId = targetResourceGroupId; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The IDs of the resources. - [WirePath("resources")] - public IList Resources { get; } - /// The target resource group. - [WirePath("targetResourceGroup")] - public ResourceIdentifier TargetResourceGroupId { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesSku.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesSku.Serialization.cs deleted file mode 100644 index 9b3032a656..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesSku.Serialization.cs +++ /dev/null @@ -1,343 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ResourcesSku : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourcesSku)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Name)) - { - writer.WritePropertyName("name"u8); - writer.WriteStringValue(Name); - } - if (Optional.IsDefined(Tier)) - { - writer.WritePropertyName("tier"u8); - writer.WriteStringValue(Tier); - } - if (Optional.IsDefined(Size)) - { - writer.WritePropertyName("size"u8); - writer.WriteStringValue(Size); - } - if (Optional.IsDefined(Family)) - { - writer.WritePropertyName("family"u8); - writer.WriteStringValue(Family); - } - if (Optional.IsDefined(Model)) - { - writer.WritePropertyName("model"u8); - writer.WriteStringValue(Model); - } - if (Optional.IsDefined(Capacity)) - { - writer.WritePropertyName("capacity"u8); - writer.WriteNumberValue(Capacity.Value); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResourcesSku IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourcesSku)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourcesSku(document.RootElement, options); - } - - internal static ResourcesSku DeserializeResourcesSku(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string name = default; - string tier = default; - string size = default; - string family = default; - string model = default; - int? capacity = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("tier"u8)) - { - tier = property.Value.GetString(); - continue; - } - if (property.NameEquals("size"u8)) - { - size = property.Value.GetString(); - continue; - } - if (property.NameEquals("family"u8)) - { - family = property.Value.GetString(); - continue; - } - if (property.NameEquals("model"u8)) - { - model = property.Value.GetString(); - continue; - } - if (property.NameEquals("capacity"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - capacity = property.Value.GetInt32(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourcesSku( - name, - tier, - size, - family, - model, - capacity, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Tier), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tier: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Tier)) - { - builder.Append(" tier: "); - if (Tier.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Tier}'''"); - } - else - { - builder.AppendLine($"'{Tier}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Size), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" size: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Size)) - { - builder.Append(" size: "); - if (Size.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Size}'''"); - } - else - { - builder.AppendLine($"'{Size}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Family), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" family: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Family)) - { - builder.Append(" family: "); - if (Family.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Family}'''"); - } - else - { - builder.AppendLine($"'{Family}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Model), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" model: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Model)) - { - builder.Append(" model: "); - if (Model.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Model}'''"); - } - else - { - builder.AppendLine($"'{Model}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Capacity), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" capacity: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Capacity)) - { - builder.Append(" capacity: "); - builder.AppendLine($"{Capacity.Value}"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourcesSku)} does not support writing '{options.Format}' format."); - } - } - - ResourcesSku IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourcesSku(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourcesSku)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesSku.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesSku.cs deleted file mode 100644 index 1aa8907276..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesSku.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// SKU for the resource. - public partial class ResourcesSku - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public ResourcesSku() - { - } - - /// Initializes a new instance of . - /// The SKU name. - /// The SKU tier. - /// The SKU size. - /// The SKU family. - /// The SKU model. - /// The SKU capacity. - /// Keeps track of any properties unknown to the library. - internal ResourcesSku(string name, string tier, string size, string family, string model, int? capacity, IDictionary serializedAdditionalRawData) - { - Name = name; - Tier = tier; - Size = size; - Family = family; - Model = model; - Capacity = capacity; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The SKU name. - [WirePath("name")] - public string Name { get; set; } - /// The SKU tier. - [WirePath("tier")] - public string Tier { get; set; } - /// The SKU size. - [WirePath("size")] - public string Size { get; set; } - /// The SKU family. - [WirePath("family")] - public string Family { get; set; } - /// The SKU model. - [WirePath("model")] - public string Model { get; set; } - /// The SKU capacity. - [WirePath("capacity")] - public int? Capacity { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SpendingLimit.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SpendingLimit.Serialization.cs deleted file mode 100644 index 1330415ea3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SpendingLimit.Serialization.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.Resources.Models -{ - internal static partial class SpendingLimitExtensions - { - public static string ToSerialString(this SpendingLimit value) => value switch - { - SpendingLimit.On => "On", - SpendingLimit.Off => "Off", - SpendingLimit.CurrentPeriodOff => "CurrentPeriodOff", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown SpendingLimit value.") - }; - - public static SpendingLimit ToSpendingLimit(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "On")) return SpendingLimit.On; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Off")) return SpendingLimit.Off; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "CurrentPeriodOff")) return SpendingLimit.CurrentPeriodOff; - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown SpendingLimit value."); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SpendingLimit.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SpendingLimit.cs deleted file mode 100644 index f1cf361866..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SpendingLimit.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.Resources.Models -{ - /// The subscription spending limit. - public enum SpendingLimit - { - /// On. - On, - /// Off. - Off, - /// CurrentPeriodOff. - CurrentPeriodOff - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubResource.cs deleted file mode 100644 index b5bc3d1195..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubResource.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Sub-resource. - public partial class SubResource - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// Resource ID. - /// Keeps track of any properties unknown to the library. - internal SubResource(ResourceIdentifier id, IDictionary serializedAdditionalRawData) - { - Id = id; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionListResult.Serialization.cs deleted file mode 100644 index 243808a807..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionListResult.Serialization.cs +++ /dev/null @@ -1,216 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class SubscriptionListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SubscriptionListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - SubscriptionListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SubscriptionListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeSubscriptionListResult(document.RootElement, options); - } - - internal static SubscriptionListResult DeserializeSubscriptionListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(SubscriptionData.DeserializeSubscriptionData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new SubscriptionListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(SubscriptionListResult)} does not support writing '{options.Format}' format."); - } - } - - SubscriptionListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeSubscriptionListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(SubscriptionListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionListResult.cs deleted file mode 100644 index 62586d3820..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionListResult.cs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Subscription list operation response. - internal partial class SubscriptionListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The URL to get the next set of results. - /// is null. - internal SubscriptionListResult(string nextLink) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - Value = new ChangeTrackingList(); - NextLink = nextLink; - } - - /// Initializes a new instance of . - /// An array of subscriptions. - /// The URL to get the next set of results. - /// Keeps track of any properties unknown to the library. - internal SubscriptionListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal SubscriptionListResult() - { - } - - /// An array of subscriptions. - public IReadOnlyList Value { get; } - /// The URL to get the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionPolicies.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionPolicies.Serialization.cs deleted file mode 100644 index 9b072238de..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionPolicies.Serialization.cs +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class SubscriptionPolicies : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SubscriptionPolicies)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(LocationPlacementId)) - { - writer.WritePropertyName("locationPlacementId"u8); - writer.WriteStringValue(LocationPlacementId); - } - if (options.Format != "W" && Optional.IsDefined(QuotaId)) - { - writer.WritePropertyName("quotaId"u8); - writer.WriteStringValue(QuotaId); - } - if (options.Format != "W" && Optional.IsDefined(SpendingLimit)) - { - writer.WritePropertyName("spendingLimit"u8); - writer.WriteStringValue(SpendingLimit.Value.ToSerialString()); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - SubscriptionPolicies IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SubscriptionPolicies)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeSubscriptionPolicies(document.RootElement, options); - } - - internal static SubscriptionPolicies DeserializeSubscriptionPolicies(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string locationPlacementId = default; - string quotaId = default; - SpendingLimit? spendingLimit = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("locationPlacementId"u8)) - { - locationPlacementId = property.Value.GetString(); - continue; - } - if (property.NameEquals("quotaId"u8)) - { - quotaId = property.Value.GetString(); - continue; - } - if (property.NameEquals("spendingLimit"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - spendingLimit = property.Value.GetString().ToSpendingLimit(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new SubscriptionPolicies(locationPlacementId, quotaId, spendingLimit, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(LocationPlacementId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" locationPlacementId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(LocationPlacementId)) - { - builder.Append(" locationPlacementId: "); - if (LocationPlacementId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{LocationPlacementId}'''"); - } - else - { - builder.AppendLine($"'{LocationPlacementId}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(QuotaId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" quotaId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(QuotaId)) - { - builder.Append(" quotaId: "); - if (QuotaId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{QuotaId}'''"); - } - else - { - builder.AppendLine($"'{QuotaId}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SpendingLimit), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" spendingLimit: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SpendingLimit)) - { - builder.Append(" spendingLimit: "); - builder.AppendLine($"'{SpendingLimit.Value.ToSerialString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(SubscriptionPolicies)} does not support writing '{options.Format}' format."); - } - } - - SubscriptionPolicies IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeSubscriptionPolicies(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(SubscriptionPolicies)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionPolicies.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionPolicies.cs deleted file mode 100644 index e953221105..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionPolicies.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Subscription policies. - public partial class SubscriptionPolicies - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal SubscriptionPolicies() - { - } - - /// Initializes a new instance of . - /// The subscription location placement ID. The ID indicates which regions are visible for a subscription. For example, a subscription with a location placement Id of Public_2014-09-01 has access to Azure public regions. - /// The subscription quota ID. - /// The subscription spending limit. - /// Keeps track of any properties unknown to the library. - internal SubscriptionPolicies(string locationPlacementId, string quotaId, SpendingLimit? spendingLimit, IDictionary serializedAdditionalRawData) - { - LocationPlacementId = locationPlacementId; - QuotaId = quotaId; - SpendingLimit = spendingLimit; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The subscription location placement ID. The ID indicates which regions are visible for a subscription. For example, a subscription with a location placement Id of Public_2014-09-01 has access to Azure public regions. - [WirePath("locationPlacementId")] - public string LocationPlacementId { get; } - /// The subscription quota ID. - [WirePath("quotaId")] - public string QuotaId { get; } - /// The subscription spending limit. - [WirePath("spendingLimit")] - public SpendingLimit? SpendingLimit { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionState.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionState.Serialization.cs deleted file mode 100644 index 51a2212e62..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionState.Serialization.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.Resources.Models -{ - internal static partial class SubscriptionStateExtensions - { - public static string ToSerialString(this SubscriptionState value) => value switch - { - SubscriptionState.Enabled => "Enabled", - SubscriptionState.Warned => "Warned", - SubscriptionState.PastDue => "PastDue", - SubscriptionState.Disabled => "Disabled", - SubscriptionState.Deleted => "Deleted", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown SubscriptionState value.") - }; - - public static SubscriptionState ToSubscriptionState(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Enabled")) return SubscriptionState.Enabled; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Warned")) return SubscriptionState.Warned; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "PastDue")) return SubscriptionState.PastDue; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Disabled")) return SubscriptionState.Disabled; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Deleted")) return SubscriptionState.Deleted; - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown SubscriptionState value."); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionState.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionState.cs deleted file mode 100644 index 2c58d11912..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionState.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.Resources.Models -{ - /// The subscription state. Possible values are Enabled, Warned, PastDue, Disabled, and Deleted. - public enum SubscriptionState - { - /// Enabled. - Enabled, - /// Warned. - Warned, - /// PastDue. - PastDue, - /// Disabled. - Disabled, - /// Deleted. - Deleted - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/Tag.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/Tag.Serialization.cs deleted file mode 100644 index 9282f0649a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/Tag.Serialization.cs +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class Tag : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(Tag)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(TagValues)) - { - writer.WritePropertyName("tags"u8); - writer.WriteStartObject(); - foreach (var item in TagValues) - { - writer.WritePropertyName(item.Key); - writer.WriteStringValue(item.Value); - } - writer.WriteEndObject(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - Tag IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(Tag)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeTag(document.RootElement, options); - } - - internal static Tag DeserializeTag(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IDictionary tags = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("tags"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - tags = dictionary; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new Tag(tags ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TagValues), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tags: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(TagValues)) - { - if (TagValues.Any()) - { - builder.Append(" tags: "); - builder.AppendLine("{"); - foreach (var item in TagValues) - { - builder.Append($" '{item.Key}': "); - if (item.Value == null) - { - builder.Append("null"); - continue; - } - if (item.Value.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{item.Value}'''"); - } - else - { - builder.AppendLine($"'{item.Value}'"); - } - } - builder.AppendLine(" }"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(Tag)} does not support writing '{options.Format}' format."); - } - } - - Tag IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeTag(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(Tag)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/Tag.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/Tag.cs deleted file mode 100644 index 694808ed76..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/Tag.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// A dictionary of name and value pairs. - public partial class Tag - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public Tag() - { - TagValues = new ChangeTrackingDictionary(); - } - - /// Initializes a new instance of . - /// Dictionary of <string>. - /// Keeps track of any properties unknown to the library. - internal Tag(IDictionary tagValues, IDictionary serializedAdditionalRawData) - { - TagValues = tagValues; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TagPatchMode.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TagPatchMode.cs deleted file mode 100644 index a9f204e236..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TagPatchMode.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The operation type for the patch API. - public readonly partial struct TagPatchMode : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public TagPatchMode(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string ReplaceValue = "Replace"; - private const string MergeValue = "Merge"; - private const string DeleteValue = "Delete"; - - /// The 'replace' option replaces the entire set of existing tags with a new set. - public static TagPatchMode Replace { get; } = new TagPatchMode(ReplaceValue); - /// The 'merge' option allows adding tags with new names and updating the values of tags with existing names. - public static TagPatchMode Merge { get; } = new TagPatchMode(MergeValue); - /// The 'delete' option allows selectively deleting tags based on given names or name/value pairs. - public static TagPatchMode Delete { get; } = new TagPatchMode(DeleteValue); - /// Determines if two values are the same. - public static bool operator ==(TagPatchMode left, TagPatchMode right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(TagPatchMode left, TagPatchMode right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator TagPatchMode(string value) => new TagPatchMode(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is TagPatchMode other && Equals(other); - /// - public bool Equals(TagPatchMode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TagResourcePatch.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TagResourcePatch.Serialization.cs deleted file mode 100644 index 3b4d3c7772..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TagResourcePatch.Serialization.cs +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class TagResourcePatch : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TagResourcePatch)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(PatchMode)) - { - writer.WritePropertyName("operation"u8); - writer.WriteStringValue(PatchMode.Value.ToString()); - } - if (Optional.IsDefined(Properties)) - { - writer.WritePropertyName("properties"u8); - writer.WriteObjectValue(Properties, options); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - TagResourcePatch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TagResourcePatch)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeTagResourcePatch(document.RootElement, options); - } - - internal static TagResourcePatch DeserializeTagResourcePatch(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - TagPatchMode? operation = default; - Tag properties = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("operation"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - operation = new TagPatchMode(property.Value.GetString()); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - properties = Tag.DeserializeTag(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new TagResourcePatch(operation, properties, serializedAdditionalRawData); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - default: - throw new FormatException($"The model {nameof(TagResourcePatch)} does not support writing '{options.Format}' format."); - } - } - - TagResourcePatch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeTagResourcePatch(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(TagResourcePatch)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TagResourcePatch.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TagResourcePatch.cs deleted file mode 100644 index dc4496a3c0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TagResourcePatch.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Wrapper resource for tags patch API request only. - public partial class TagResourcePatch - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public TagResourcePatch() - { - } - - /// Initializes a new instance of . - /// The operation type for the patch API. - /// The set of tags. - /// Keeps track of any properties unknown to the library. - internal TagResourcePatch(TagPatchMode? patchMode, Tag properties, IDictionary serializedAdditionalRawData) - { - PatchMode = patchMode; - Properties = properties; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The operation type for the patch API. - [WirePath("operation")] - public TagPatchMode? PatchMode { get; set; } - /// The set of tags. - internal Tag Properties { get; set; } - /// Dictionary of <string>. - [WirePath("properties.tags")] - public IDictionary TagValues - { - get - { - if (Properties is null) - Properties = new Tag(); - return Properties.TagValues; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantCategory.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantCategory.Serialization.cs deleted file mode 100644 index a3d824a90a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantCategory.Serialization.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; - -namespace Azure.ResourceManager.Resources.Models -{ - internal static partial class TenantCategoryExtensions - { - public static string ToSerialString(this TenantCategory value) => value switch - { - TenantCategory.Home => "Home", - TenantCategory.ProjectedBy => "ProjectedBy", - TenantCategory.ManagedBy => "ManagedBy", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown TenantCategory value.") - }; - - public static TenantCategory ToTenantCategory(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "Home")) return TenantCategory.Home; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "ProjectedBy")) return TenantCategory.ProjectedBy; - if (StringComparer.OrdinalIgnoreCase.Equals(value, "ManagedBy")) return TenantCategory.ManagedBy; - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown TenantCategory value."); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantCategory.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantCategory.cs deleted file mode 100644 index 4de42a1b2f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantCategory.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -namespace Azure.ResourceManager.Resources.Models -{ - /// Category of the tenant. - public enum TenantCategory - { - /// Home. - Home, - /// ProjectedBy. - ProjectedBy, - /// ManagedBy. - ManagedBy - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantListResult.Serialization.cs deleted file mode 100644 index 2f42b18f55..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantListResult.Serialization.cs +++ /dev/null @@ -1,216 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class TenantListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TenantListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - TenantListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TenantListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeTenantListResult(document.RootElement, options); - } - - internal static TenantListResult DeserializeTenantListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(TenantData.DeserializeTenantData(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new TenantListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(TenantListResult)} does not support writing '{options.Format}' format."); - } - } - - TenantListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeTenantListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(TenantListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantListResult.cs deleted file mode 100644 index 82c47daaf1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantListResult.cs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Tenant Ids information. - internal partial class TenantListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The URL to use for getting the next set of results. - /// is null. - internal TenantListResult(string nextLink) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - Value = new ChangeTrackingList(); - NextLink = nextLink; - } - - /// Initializes a new instance of . - /// An array of tenants. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal TenantListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal TenantListResult() - { - } - - /// An array of tenants. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProvider.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProvider.Serialization.cs deleted file mode 100644 index 200c7232ad..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProvider.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class TenantResourceProvider : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TenantResourceProvider)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Namespace)) - { - writer.WritePropertyName("namespace"u8); - writer.WriteStringValue(Namespace); - } - if (options.Format != "W" && Optional.IsCollectionDefined(ResourceTypes)) - { - writer.WritePropertyName("resourceTypes"u8); - writer.WriteStartArray(); - foreach (var item in ResourceTypes) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - TenantResourceProvider IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TenantResourceProvider)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeTenantResourceProvider(document.RootElement, options); - } - - internal static TenantResourceProvider DeserializeTenantResourceProvider(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @namespace = default; - IReadOnlyList resourceTypes = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("namespace"u8)) - { - @namespace = property.Value.GetString(); - continue; - } - if (property.NameEquals("resourceTypes"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ProviderResourceType.DeserializeProviderResourceType(item, options)); - } - resourceTypes = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new TenantResourceProvider(@namespace, resourceTypes ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Namespace), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" namespace: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Namespace)) - { - builder.Append(" namespace: "); - if (Namespace.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Namespace}'''"); - } - else - { - builder.AppendLine($"'{Namespace}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ResourceTypes), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" resourceTypes: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ResourceTypes)) - { - if (ResourceTypes.Any()) - { - builder.Append(" resourceTypes: "); - builder.AppendLine("["); - foreach (var item in ResourceTypes) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " resourceTypes: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(TenantResourceProvider)} does not support writing '{options.Format}' format."); - } - } - - TenantResourceProvider IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeTenantResourceProvider(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(TenantResourceProvider)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProvider.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProvider.cs deleted file mode 100644 index c32fa3cc1a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProvider.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Resource provider information. - public partial class TenantResourceProvider - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal TenantResourceProvider() - { - ResourceTypes = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The namespace of the resource provider. - /// The collection of provider resource types. - /// Keeps track of any properties unknown to the library. - internal TenantResourceProvider(string @namespace, IReadOnlyList resourceTypes, IDictionary serializedAdditionalRawData) - { - Namespace = @namespace; - ResourceTypes = resourceTypes; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The namespace of the resource provider. - [WirePath("namespace")] - public string Namespace { get; } - /// The collection of provider resource types. - [WirePath("resourceTypes")] - public IReadOnlyList ResourceTypes { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProviderListResult.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProviderListResult.Serialization.cs deleted file mode 100644 index 29cfc732a4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProviderListResult.Serialization.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - internal partial class TenantResourceProviderListResult : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TenantResourceProviderListResult)} does not support writing '{format}' format."); - } - - if (Optional.IsCollectionDefined(Value)) - { - writer.WritePropertyName("value"u8); - writer.WriteStartArray(); - foreach (var item in Value) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(NextLink)) - { - writer.WritePropertyName("nextLink"u8); - writer.WriteStringValue(NextLink); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - TenantResourceProviderListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TenantResourceProviderListResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeTenantResourceProviderListResult(document.RootElement, options); - } - - internal static TenantResourceProviderListResult DeserializeTenantResourceProviderListResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - IReadOnlyList value = default; - string nextLink = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(TenantResourceProvider.DeserializeTenantResourceProvider(item, options)); - } - value = array; - continue; - } - if (property.NameEquals("nextLink"u8)) - { - nextLink = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new TenantResourceProviderListResult(value ?? new ChangeTrackingList(), nextLink, serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Value), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" value: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Value)) - { - if (Value.Any()) - { - builder.Append(" value: "); - builder.AppendLine("["); - foreach (var item in Value) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " value: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NextLink), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nextLink: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(NextLink)) - { - builder.Append(" nextLink: "); - if (NextLink.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{NextLink}'''"); - } - else - { - builder.AppendLine($"'{NextLink}'"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(TenantResourceProviderListResult)} does not support writing '{options.Format}' format."); - } - } - - TenantResourceProviderListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeTenantResourceProviderListResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(TenantResourceProviderListResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProviderListResult.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProviderListResult.cs deleted file mode 100644 index 44043f0767..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProviderListResult.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.ResourceManager.Resources.Models -{ - /// List of resource providers. - internal partial class TenantResourceProviderListResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal TenantResourceProviderListResult() - { - Value = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// An array of resource providers. - /// The URL to use for getting the next set of results. - /// Keeps track of any properties unknown to the library. - internal TenantResourceProviderListResult(IReadOnlyList value, string nextLink, IDictionary serializedAdditionalRawData) - { - Value = value; - NextLink = nextLink; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// An array of resource providers. - public IReadOnlyList Value { get; } - /// The URL to use for getting the next set of results. - public string NextLink { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TrackedResourceExtendedData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TrackedResourceExtendedData.Serialization.cs deleted file mode 100644 index ab343d86e9..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TrackedResourceExtendedData.Serialization.cs +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class TrackedResourceExtendedData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TrackedResourceExtendedData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - if (Optional.IsDefined(ExtendedLocation)) - { - writer.WritePropertyName("extendedLocation"u8); - JsonSerializer.Serialize(writer, ExtendedLocation); - } - } - - TrackedResourceExtendedData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TrackedResourceExtendedData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeTrackedResourceExtendedData(document.RootElement, options); - } - - internal static TrackedResourceExtendedData DeserializeTrackedResourceExtendedData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ExtendedLocation extendedLocation = default; - IDictionary tags = default; - AzureLocation location = default; - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("extendedLocation"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - extendedLocation = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("tags"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - tags = dictionary; - continue; - } - if (property.NameEquals("location"u8)) - { - location = new AzureLocation(property.Value.GetString()); - continue; - } - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new TrackedResourceExtendedData( - id, - name, - type, - systemData, - tags ?? new ChangeTrackingDictionary(), - location, - extendedLocation, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Location), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" location: "); - builder.AppendLine(propertyOverride); - } - else - { - builder.Append(" location: "); - builder.AppendLine($"'{Location.ToString()}'"); - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Tags), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tags: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Tags)) - { - if (Tags.Any()) - { - builder.Append(" tags: "); - builder.AppendLine("{"); - foreach (var item in Tags) - { - builder.Append($" '{item.Key}': "); - if (item.Value == null) - { - builder.Append("null"); - continue; - } - if (item.Value.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{item.Value}'''"); - } - else - { - builder.AppendLine($"'{item.Value}'"); - } - } - builder.AppendLine(" }"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ExtendedLocation), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" extendedLocation: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ExtendedLocation)) - { - builder.Append(" extendedLocation: "); - BicepSerializationHelpers.AppendChildObject(builder, ExtendedLocation, options, 2, false, " extendedLocation: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(TrackedResourceExtendedData)} does not support writing '{options.Format}' format."); - } - } - - TrackedResourceExtendedData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeTrackedResourceExtendedData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(TrackedResourceExtendedData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TrackedResourceExtendedData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TrackedResourceExtendedData.cs deleted file mode 100644 index 1474b682eb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/TrackedResourceExtendedData.cs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; - -namespace Azure.ResourceManager.Resources.Models -{ - /// Specified resource. - public partial class TrackedResourceExtendedData : TrackedResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private protected IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The location. - public TrackedResourceExtendedData(AzureLocation location) : base(location) - { - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The tags. - /// The location. - /// Resource extended location. - /// Keeps track of any properties unknown to the library. - internal TrackedResourceExtendedData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, IDictionary tags, AzureLocation location, ExtendedLocation extendedLocation, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData, tags, location) - { - ExtendedLocation = extendedLocation; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal TrackedResourceExtendedData() - { - } - - /// Resource extended location. - [WirePath("extendedLocation")] - public ExtendedLocation ExtendedLocation { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ZoneMapping.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ZoneMapping.Serialization.cs deleted file mode 100644 index 7d0844bc01..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ZoneMapping.Serialization.cs +++ /dev/null @@ -1,228 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - public partial class ZoneMapping : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ZoneMapping)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(Location)) - { - writer.WritePropertyName("location"u8); - writer.WriteStringValue(Location.Value); - } - if (Optional.IsCollectionDefined(Zones)) - { - writer.WritePropertyName("zones"u8); - writer.WriteStartArray(); - foreach (var item in Zones) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ZoneMapping IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ZoneMapping)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeZoneMapping(document.RootElement, options); - } - - internal static ZoneMapping DeserializeZoneMapping(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - AzureLocation? location = default; - IReadOnlyList zones = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("location"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - location = new AzureLocation(property.Value.GetString()); - continue; - } - if (property.NameEquals("zones"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - zones = array; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ZoneMapping(location, zones ?? new ChangeTrackingList(), serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Location), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" location: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Location)) - { - builder.Append(" location: "); - builder.AppendLine($"'{Location.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Zones), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" zones: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Zones)) - { - if (Zones.Any()) - { - builder.Append(" zones: "); - builder.AppendLine("["); - foreach (var item in Zones) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ZoneMapping)} does not support writing '{options.Format}' format."); - } - } - - ZoneMapping IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeZoneMapping(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ZoneMapping)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ZoneMapping.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ZoneMapping.cs deleted file mode 100644 index 78773bb967..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/Models/ZoneMapping.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.ResourceManager.Resources.Models -{ - /// The ZoneMapping. - public partial class ZoneMapping - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal ZoneMapping() - { - Zones = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The location of the zone mapping. - /// - /// Keeps track of any properties unknown to the library. - internal ZoneMapping(AzureLocation? location, IReadOnlyList zones, IDictionary serializedAdditionalRawData) - { - Location = location; - Zones = zones; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The location of the zone mapping. - [WirePath("location")] - public AzureLocation? Location { get; } - /// Gets the zones. - [WirePath("zones")] - public IReadOnlyList Zones { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentCollection.cs deleted file mode 100644 index c424f0598d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentCollection.cs +++ /dev/null @@ -1,630 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.ManagementGroups; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetPolicyAssignments method from an instance of . - /// - public partial class PolicyAssignmentCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _policyAssignmentClientDiagnostics; - private readonly PolicyAssignmentsRestOperations _policyAssignmentRestClient; - - /// Initializes a new instance of the class for mocking. - protected PolicyAssignmentCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal PolicyAssignmentCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _policyAssignmentClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", PolicyAssignmentResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(PolicyAssignmentResource.ResourceType, out string policyAssignmentApiVersion); - _policyAssignmentRestClient = new PolicyAssignmentsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, policyAssignmentApiVersion); - } - - /// - /// This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Create - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy assignment. - /// Parameters for the policy assignment. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string policyAssignmentName, PolicyAssignmentData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _policyAssignmentRestClient.CreateAsync(Id, policyAssignmentName, data, cancellationToken).ConfigureAwait(false); - var uri = _policyAssignmentRestClient.CreateCreateRequestUri(Id, policyAssignmentName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new PolicyAssignmentResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Create - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy assignment. - /// Parameters for the policy assignment. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string policyAssignmentName, PolicyAssignmentData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = _policyAssignmentRestClient.Create(Id, policyAssignmentName, data, cancellationToken); - var uri = _policyAssignmentRestClient.CreateCreateRequestUri(Id, policyAssignmentName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new PolicyAssignmentResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a single policy assignment, given its name and the scope it was created at. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentCollection.Get"); - scope.Start(); - try - { - var response = await _policyAssignmentRestClient.GetAsync(Id, policyAssignmentName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new PolicyAssignmentResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a single policy assignment, given its name and the scope it was created at. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentCollection.Get"); - scope.Start(); - try - { - var response = _policyAssignmentRestClient.Get(Id, policyAssignmentName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new PolicyAssignmentResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the list of all policy assignments associated with the given resource group in the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource group, including those that apply directly or apply from containing scopes, as well as any applied to resources contained within the resource group. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource group, which is everything in the unfiltered list except those applied to resources contained within the resource group. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments - /// - /// - /// Operation Id - /// PolicyAssignments_ListForResourceGroup - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyAssignments - /// - /// - /// Operation Id - /// PolicyAssignments_ListForResource - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyAssignments - /// - /// - /// Operation Id - /// PolicyAssignments_ListForManagementGroup - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyAssignments - /// - /// - /// Operation Id - /// PolicyAssignments_List - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - if (Id.ResourceType == ResourceGroupResource.ResourceType) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _policyAssignmentRestClient.CreateListForResourceGroupRequest(Id.SubscriptionId, Id.ResourceGroupName, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _policyAssignmentRestClient.CreateListForResourceGroupNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new PolicyAssignmentResource(Client, PolicyAssignmentData.DeserializePolicyAssignmentData(e)), _policyAssignmentClientDiagnostics, Pipeline, "PolicyAssignmentCollection.GetAll", "value", "nextLink", cancellationToken); - } - else if (Id.ResourceType == ManagementGroupResource.ResourceType) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _policyAssignmentRestClient.CreateListForManagementGroupRequest(Id.Name, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _policyAssignmentRestClient.CreateListForManagementGroupNextPageRequest(nextLink, Id.Name, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new PolicyAssignmentResource(Client, PolicyAssignmentData.DeserializePolicyAssignmentData(e)), _policyAssignmentClientDiagnostics, Pipeline, "PolicyAssignmentCollection.GetAll", "value", "nextLink", cancellationToken); - } - else if (Id.ResourceType == SubscriptionResource.ResourceType) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _policyAssignmentRestClient.CreateListRequest(Id.SubscriptionId, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _policyAssignmentRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new PolicyAssignmentResource(Client, PolicyAssignmentData.DeserializePolicyAssignmentData(e)), _policyAssignmentClientDiagnostics, Pipeline, "PolicyAssignmentCollection.GetAll", "value", "nextLink", cancellationToken); - } - else - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _policyAssignmentRestClient.CreateListForResourceRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.ResourceType.Namespace, Id.Parent.SubstringAfterProviderNamespace(), Id.ResourceType.GetLastType(), Id.Name, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _policyAssignmentRestClient.CreateListForResourceNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.ResourceType.Namespace, Id.Parent.SubstringAfterProviderNamespace(), Id.ResourceType.GetLastType(), Id.Name, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new PolicyAssignmentResource(Client, PolicyAssignmentData.DeserializePolicyAssignmentData(e)), _policyAssignmentClientDiagnostics, Pipeline, "PolicyAssignmentCollection.GetAll", "value", "nextLink", cancellationToken); - } - } - - /// - /// This operation retrieves the list of all policy assignments associated with the given resource group in the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource group, including those that apply directly or apply from containing scopes, as well as any applied to resources contained within the resource group. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource group, which is everything in the unfiltered list except those applied to resources contained within the resource group. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments - /// - /// - /// Operation Id - /// PolicyAssignments_ListForResourceGroup - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyAssignments - /// - /// - /// Operation Id - /// PolicyAssignments_ListForResource - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// Request Path - /// /providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyAssignments - /// - /// - /// Operation Id - /// PolicyAssignments_ListForManagementGroup - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyAssignments - /// - /// - /// Operation Id - /// PolicyAssignments_List - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - if (Id.ResourceType == ResourceGroupResource.ResourceType) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _policyAssignmentRestClient.CreateListForResourceGroupRequest(Id.SubscriptionId, Id.ResourceGroupName, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _policyAssignmentRestClient.CreateListForResourceGroupNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new PolicyAssignmentResource(Client, PolicyAssignmentData.DeserializePolicyAssignmentData(e)), _policyAssignmentClientDiagnostics, Pipeline, "PolicyAssignmentCollection.GetAll", "value", "nextLink", cancellationToken); - } - else if (Id.ResourceType == ManagementGroupResource.ResourceType) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _policyAssignmentRestClient.CreateListForManagementGroupRequest(Id.Name, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _policyAssignmentRestClient.CreateListForManagementGroupNextPageRequest(nextLink, Id.Name, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new PolicyAssignmentResource(Client, PolicyAssignmentData.DeserializePolicyAssignmentData(e)), _policyAssignmentClientDiagnostics, Pipeline, "PolicyAssignmentCollection.GetAll", "value", "nextLink", cancellationToken); - } - else if (Id.ResourceType == SubscriptionResource.ResourceType) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _policyAssignmentRestClient.CreateListRequest(Id.SubscriptionId, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _policyAssignmentRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new PolicyAssignmentResource(Client, PolicyAssignmentData.DeserializePolicyAssignmentData(e)), _policyAssignmentClientDiagnostics, Pipeline, "PolicyAssignmentCollection.GetAll", "value", "nextLink", cancellationToken); - } - else - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _policyAssignmentRestClient.CreateListForResourceRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.ResourceType.Namespace, Id.Parent.SubstringAfterProviderNamespace(), Id.ResourceType.GetLastType(), Id.Name, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _policyAssignmentRestClient.CreateListForResourceNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.ResourceType.Namespace, Id.Parent.SubstringAfterProviderNamespace(), Id.ResourceType.GetLastType(), Id.Name, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new PolicyAssignmentResource(Client, PolicyAssignmentData.DeserializePolicyAssignmentData(e)), _policyAssignmentClientDiagnostics, Pipeline, "PolicyAssignmentCollection.GetAll", "value", "nextLink", cancellationToken); - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentCollection.Exists"); - scope.Start(); - try - { - var response = await _policyAssignmentRestClient.GetAsync(Id, policyAssignmentName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentCollection.Exists"); - scope.Start(); - try - { - var response = _policyAssignmentRestClient.Get(Id, policyAssignmentName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _policyAssignmentRestClient.GetAsync(Id, policyAssignmentName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new PolicyAssignmentResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentCollection.GetIfExists"); - scope.Start(); - try - { - var response = _policyAssignmentRestClient.Get(Id, policyAssignmentName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new PolicyAssignmentResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentData.Serialization.cs deleted file mode 100644 index 75d365aacf..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentData.Serialization.cs +++ /dev/null @@ -1,760 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class PolicyAssignmentData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyAssignmentData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - if (Optional.IsDefined(Location)) - { - writer.WritePropertyName("location"u8); - writer.WriteStringValue(Location.Value); - } - if (Optional.IsDefined(ManagedIdentity)) - { - writer.WritePropertyName("identity"u8); - JsonSerializer.Serialize(writer, ManagedIdentity); - } - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (Optional.IsDefined(PolicyDefinitionId)) - { - writer.WritePropertyName("policyDefinitionId"u8); - writer.WriteStringValue(PolicyDefinitionId); - } - if (options.Format != "W" && Optional.IsDefined(Scope)) - { - writer.WritePropertyName("scope"u8); - writer.WriteStringValue(Scope); - } - if (Optional.IsCollectionDefined(ExcludedScopes)) - { - writer.WritePropertyName("notScopes"u8); - writer.WriteStartArray(); - foreach (var item in ExcludedScopes) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(Parameters)) - { - writer.WritePropertyName("parameters"u8); - writer.WriteStartObject(); - foreach (var item in Parameters) - { - writer.WritePropertyName(item.Key); - writer.WriteObjectValue(item.Value, options); - } - writer.WriteEndObject(); - } - if (Optional.IsDefined(Description)) - { - writer.WritePropertyName("description"u8); - writer.WriteStringValue(Description); - } - if (Optional.IsDefined(Metadata)) - { - writer.WritePropertyName("metadata"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(Metadata); -#else - using (JsonDocument document = JsonDocument.Parse(Metadata, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - if (Optional.IsDefined(EnforcementMode)) - { - writer.WritePropertyName("enforcementMode"u8); - writer.WriteStringValue(EnforcementMode.Value.ToString()); - } - if (Optional.IsCollectionDefined(NonComplianceMessages)) - { - writer.WritePropertyName("nonComplianceMessages"u8); - writer.WriteStartArray(); - foreach (var item in NonComplianceMessages) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(ResourceSelectors)) - { - writer.WritePropertyName("resourceSelectors"u8); - writer.WriteStartArray(); - foreach (var item in ResourceSelectors) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(Overrides)) - { - writer.WritePropertyName("overrides"u8); - writer.WriteStartArray(); - foreach (var item in Overrides) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - writer.WriteEndObject(); - } - - PolicyAssignmentData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyAssignmentData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicyAssignmentData(document.RootElement, options); - } - - internal static PolicyAssignmentData DeserializePolicyAssignmentData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - AzureLocation? location = default; - ManagedServiceIdentity identity = default; - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - string displayName = default; - string policyDefinitionId = default; - string scope = default; - IList notScopes = default; - IDictionary parameters = default; - string description = default; - BinaryData metadata = default; - EnforcementMode? enforcementMode = default; - IList nonComplianceMessages = default; - IList resourceSelectors = default; - IList overrides = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("location"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - location = new AzureLocation(property.Value.GetString()); - continue; - } - if (property.NameEquals("identity"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - identity = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("displayName"u8)) - { - displayName = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("policyDefinitionId"u8)) - { - policyDefinitionId = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("scope"u8)) - { - scope = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("notScopes"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - notScopes = array; - continue; - } - if (property0.NameEquals("parameters"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property1 in property0.Value.EnumerateObject()) - { - dictionary.Add(property1.Name, ArmPolicyParameterValue.DeserializeArmPolicyParameterValue(property1.Value, options)); - } - parameters = dictionary; - continue; - } - if (property0.NameEquals("description"u8)) - { - description = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("metadata"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - metadata = BinaryData.FromString(property0.Value.GetRawText()); - continue; - } - if (property0.NameEquals("enforcementMode"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - enforcementMode = new EnforcementMode(property0.Value.GetString()); - continue; - } - if (property0.NameEquals("nonComplianceMessages"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(NonComplianceMessage.DeserializeNonComplianceMessage(item, options)); - } - nonComplianceMessages = array; - continue; - } - if (property0.NameEquals("resourceSelectors"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(ResourceSelector.DeserializeResourceSelector(item, options)); - } - resourceSelectors = array; - continue; - } - if (property0.NameEquals("overrides"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(PolicyOverride.DeserializePolicyOverride(item, options)); - } - overrides = array; - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicyAssignmentData( - id, - name, - type, - systemData, - location, - identity, - displayName, - policyDefinitionId, - scope, - notScopes ?? new ChangeTrackingList(), - parameters ?? new ChangeTrackingDictionary(), - description, - metadata, - enforcementMode, - nonComplianceMessages ?? new ChangeTrackingList(), - resourceSelectors ?? new ChangeTrackingList(), - overrides ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Location), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" location: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Location)) - { - builder.Append(" location: "); - builder.AppendLine($"'{Location.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ManagedIdentity), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" identity: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ManagedIdentity)) - { - builder.Append(" identity: "); - BicepSerializationHelpers.AppendChildObject(builder, ManagedIdentity, options, 2, false, " identity: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.Append(" properties:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyDefinitionId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyDefinitionId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PolicyDefinitionId)) - { - builder.Append(" policyDefinitionId: "); - if (PolicyDefinitionId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{PolicyDefinitionId}'''"); - } - else - { - builder.AppendLine($"'{PolicyDefinitionId}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Scope), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" scope: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Scope)) - { - builder.Append(" scope: "); - if (Scope.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Scope}'''"); - } - else - { - builder.AppendLine($"'{Scope}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ExcludedScopes), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" notScopes: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ExcludedScopes)) - { - if (ExcludedScopes.Any()) - { - builder.Append(" notScopes: "); - builder.AppendLine("["); - foreach (var item in ExcludedScopes) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Parameters), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parameters: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Parameters)) - { - if (Parameters.Any()) - { - builder.Append(" parameters: "); - builder.AppendLine("{"); - foreach (var item in Parameters) - { - builder.Append($" '{item.Key}': "); - BicepSerializationHelpers.AppendChildObject(builder, item.Value, options, 6, false, " parameters: "); - } - builder.AppendLine(" }"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Description), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" description: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Description)) - { - builder.Append(" description: "); - if (Description.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Description}'''"); - } - else - { - builder.AppendLine($"'{Description}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Metadata), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" metadata: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Metadata)) - { - builder.Append(" metadata: "); - builder.AppendLine($"'{Metadata.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(EnforcementMode), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" enforcementMode: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(EnforcementMode)) - { - builder.Append(" enforcementMode: "); - builder.AppendLine($"'{EnforcementMode.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(NonComplianceMessages), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" nonComplianceMessages: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(NonComplianceMessages)) - { - if (NonComplianceMessages.Any()) - { - builder.Append(" nonComplianceMessages: "); - builder.AppendLine("["); - foreach (var item in NonComplianceMessages) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 6, true, " nonComplianceMessages: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ResourceSelectors), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" resourceSelectors: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ResourceSelectors)) - { - if (ResourceSelectors.Any()) - { - builder.Append(" resourceSelectors: "); - builder.AppendLine("["); - foreach (var item in ResourceSelectors) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 6, true, " resourceSelectors: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Overrides), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" overrides: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Overrides)) - { - if (Overrides.Any()) - { - builder.Append(" overrides: "); - builder.AppendLine("["); - foreach (var item in Overrides) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 6, true, " overrides: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine(" }"); - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PolicyAssignmentData)} does not support writing '{options.Format}' format."); - } - } - - PolicyAssignmentData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicyAssignmentData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicyAssignmentData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentData.cs deleted file mode 100644 index f0a246cdc3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentData.cs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the PolicyAssignment data model. - /// The policy assignment. - /// - public partial class PolicyAssignmentData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public PolicyAssignmentData() - { - ExcludedScopes = new ChangeTrackingList(); - Parameters = new ChangeTrackingDictionary(); - NonComplianceMessages = new ChangeTrackingList(); - ResourceSelectors = new ChangeTrackingList(); - Overrides = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The location of the policy assignment. Only required when utilizing managed identity. - /// The managed identity associated with the policy assignment. Current supported identity types: None, SystemAssigned, UserAssigned. - /// The display name of the policy assignment. - /// The ID of the policy definition or policy set definition being assigned. - /// The scope for the policy assignment. - /// The policy's excluded scopes. - /// The parameter values for the assigned policy rule. The keys are the parameter names. - /// This message will be part of response in case of policy violation. - /// The policy assignment metadata. Metadata is an open ended object and is typically a collection of key value pairs. - /// The policy assignment enforcement mode. Possible values are Default and DoNotEnforce. - /// The messages that describe why a resource is non-compliant with the policy. - /// The resource selector list to filter policies by resource properties. - /// The policy property value override. - /// Keeps track of any properties unknown to the library. - internal PolicyAssignmentData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, AzureLocation? location, ManagedServiceIdentity managedIdentity, string displayName, string policyDefinitionId, string scope, IList excludedScopes, IDictionary parameters, string description, BinaryData metadata, EnforcementMode? enforcementMode, IList nonComplianceMessages, IList resourceSelectors, IList overrides, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - Location = location; - ManagedIdentity = managedIdentity; - DisplayName = displayName; - PolicyDefinitionId = policyDefinitionId; - Scope = scope; - ExcludedScopes = excludedScopes; - Parameters = parameters; - Description = description; - Metadata = metadata; - EnforcementMode = enforcementMode; - NonComplianceMessages = nonComplianceMessages; - ResourceSelectors = resourceSelectors; - Overrides = overrides; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The location of the policy assignment. Only required when utilizing managed identity. - [WirePath("location")] - public AzureLocation? Location { get; set; } - /// The managed identity associated with the policy assignment. Current supported identity types: None, SystemAssigned, UserAssigned. - [WirePath("identity")] - public ManagedServiceIdentity ManagedIdentity { get; set; } - /// The display name of the policy assignment. - [WirePath("properties.displayName")] - public string DisplayName { get; set; } - /// The ID of the policy definition or policy set definition being assigned. - [WirePath("properties.policyDefinitionId")] - public string PolicyDefinitionId { get; set; } - /// The scope for the policy assignment. - [WirePath("properties.scope")] - public string Scope { get; } - /// The policy's excluded scopes. - [WirePath("properties.notScopes")] - public IList ExcludedScopes { get; } - /// The parameter values for the assigned policy rule. The keys are the parameter names. - [WirePath("properties.parameters")] - public IDictionary Parameters { get; } - /// This message will be part of response in case of policy violation. - [WirePath("properties.description")] - public string Description { get; set; } - /// - /// The policy assignment metadata. Metadata is an open ended object and is typically a collection of key value pairs. - /// - /// To assign an object to this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("properties.metadata")] - public BinaryData Metadata { get; set; } - /// The policy assignment enforcement mode. Possible values are Default and DoNotEnforce. - [WirePath("properties.enforcementMode")] - public EnforcementMode? EnforcementMode { get; set; } - /// The messages that describe why a resource is non-compliant with the policy. - [WirePath("properties.nonComplianceMessages")] - public IList NonComplianceMessages { get; } - /// The resource selector list to filter policies by resource properties. - [WirePath("properties.resourceSelectors")] - public IList ResourceSelectors { get; } - /// The policy property value override. - [WirePath("properties.overrides")] - public IList Overrides { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentResource.Serialization.cs deleted file mode 100644 index 407fb6014f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class PolicyAssignmentResource : IJsonModel - { - private static PolicyAssignmentData s_dataDeserializationInstance; - private static PolicyAssignmentData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - PolicyAssignmentData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - PolicyAssignmentData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentResource.cs deleted file mode 100644 index be2bed645c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentResource.cs +++ /dev/null @@ -1,342 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a PolicyAssignment along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetPolicyAssignmentResource method. - /// Otherwise you can get one from its parent resource using the GetPolicyAssignment method. - /// - public partial class PolicyAssignmentResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The scope. - /// The policyAssignmentName. - public static ResourceIdentifier CreateResourceIdentifier(string scope, string policyAssignmentName) - { - var resourceId = $"{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _policyAssignmentClientDiagnostics; - private readonly PolicyAssignmentsRestOperations _policyAssignmentRestClient; - private readonly PolicyAssignmentData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Authorization/policyAssignments"; - - /// Initializes a new instance of the class for mocking. - protected PolicyAssignmentResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal PolicyAssignmentResource(ArmClient client, PolicyAssignmentData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal PolicyAssignmentResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _policyAssignmentClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string policyAssignmentApiVersion); - _policyAssignmentRestClient = new PolicyAssignmentsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, policyAssignmentApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual PolicyAssignmentData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// This operation retrieves a single policy assignment, given its name and the scope it was created at. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentResource.Get"); - scope.Start(); - try - { - var response = await _policyAssignmentRestClient.GetAsync(Id.Parent, Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new PolicyAssignmentResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a single policy assignment, given its name and the scope it was created at. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Get - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentResource.Get"); - scope.Start(); - try - { - var response = _policyAssignmentRestClient.Get(Id.Parent, Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new PolicyAssignmentResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes a policy assignment, given its name and the scope it was created in. The scope of a policy assignment is the part of its ID preceding '/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Delete - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual async Task> DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentResource.Delete"); - scope.Start(); - try - { - var response = await _policyAssignmentRestClient.DeleteAsync(Id.Parent, Id.Name, cancellationToken).ConfigureAwait(false); - var uri = _policyAssignmentRestClient.CreateDeleteRequestUri(Id.Parent, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new PolicyAssignmentResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes a policy assignment, given its name and the scope it was created in. The scope of a policy assignment is the part of its ID preceding '/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Delete - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentResource.Delete"); - scope.Start(); - try - { - var response = _policyAssignmentRestClient.Delete(Id.Parent, Id.Name, cancellationToken); - var uri = _policyAssignmentRestClient.CreateDeleteRequestUri(Id.Parent, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new PolicyAssignmentResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Update - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Parameters for policy assignment patch request. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(PolicyAssignmentPatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(patch, nameof(patch)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentResource.Update"); - scope.Start(); - try - { - var response = await _policyAssignmentRestClient.UpdateAsync(Id.Parent, Id.Name, patch, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new PolicyAssignmentResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} - /// - /// - /// Operation Id - /// PolicyAssignments_Update - /// - /// - /// Default Api Version - /// 2022-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Parameters for policy assignment patch request. - /// The cancellation token to use. - /// is null. - public virtual Response Update(PolicyAssignmentPatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(patch, nameof(patch)); - - using var scope = _policyAssignmentClientDiagnostics.CreateScope("PolicyAssignmentResource.Update"); - scope.Start(); - try - { - var response = _policyAssignmentRestClient.Update(Id.Parent, Id.Name, patch, cancellationToken); - return Response.FromValue(new PolicyAssignmentResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyDefinitionData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyDefinitionData.Serialization.cs deleted file mode 100644 index 0e82e86edf..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyDefinitionData.Serialization.cs +++ /dev/null @@ -1,492 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class PolicyDefinitionData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyDefinitionData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (Optional.IsDefined(PolicyType)) - { - writer.WritePropertyName("policyType"u8); - writer.WriteStringValue(PolicyType.Value.ToString()); - } - if (Optional.IsDefined(Mode)) - { - writer.WritePropertyName("mode"u8); - writer.WriteStringValue(Mode); - } - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (Optional.IsDefined(Description)) - { - writer.WritePropertyName("description"u8); - writer.WriteStringValue(Description); - } - if (Optional.IsDefined(PolicyRule)) - { - writer.WritePropertyName("policyRule"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(PolicyRule); -#else - using (JsonDocument document = JsonDocument.Parse(PolicyRule, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - if (Optional.IsDefined(Metadata)) - { - writer.WritePropertyName("metadata"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(Metadata); -#else - using (JsonDocument document = JsonDocument.Parse(Metadata, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - if (Optional.IsCollectionDefined(Parameters)) - { - writer.WritePropertyName("parameters"u8); - writer.WriteStartObject(); - foreach (var item in Parameters) - { - writer.WritePropertyName(item.Key); - writer.WriteObjectValue(item.Value, options); - } - writer.WriteEndObject(); - } - writer.WriteEndObject(); - } - - PolicyDefinitionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicyDefinitionData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicyDefinitionData(document.RootElement, options); - } - - internal static PolicyDefinitionData DeserializePolicyDefinitionData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - PolicyType? policyType = default; - string mode = default; - string displayName = default; - string description = default; - BinaryData policyRule = default; - BinaryData metadata = default; - IDictionary parameters = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("policyType"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - policyType = new PolicyType(property0.Value.GetString()); - continue; - } - if (property0.NameEquals("mode"u8)) - { - mode = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("displayName"u8)) - { - displayName = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("description"u8)) - { - description = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("policyRule"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - policyRule = BinaryData.FromString(property0.Value.GetRawText()); - continue; - } - if (property0.NameEquals("metadata"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - metadata = BinaryData.FromString(property0.Value.GetRawText()); - continue; - } - if (property0.NameEquals("parameters"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property1 in property0.Value.EnumerateObject()) - { - dictionary.Add(property1.Name, ArmPolicyParameter.DeserializeArmPolicyParameter(property1.Value, options)); - } - parameters = dictionary; - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicyDefinitionData( - id, - name, - type, - systemData, - policyType, - mode, - displayName, - description, - policyRule, - metadata, - parameters ?? new ChangeTrackingDictionary(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.Append(" properties:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PolicyType)) - { - builder.Append(" policyType: "); - builder.AppendLine($"'{PolicyType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Mode), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" mode: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Mode)) - { - builder.Append(" mode: "); - if (Mode.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Mode}'''"); - } - else - { - builder.AppendLine($"'{Mode}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Description), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" description: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Description)) - { - builder.Append(" description: "); - if (Description.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Description}'''"); - } - else - { - builder.AppendLine($"'{Description}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyRule), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyRule: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PolicyRule)) - { - builder.Append(" policyRule: "); - builder.AppendLine($"'{PolicyRule.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Metadata), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" metadata: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Metadata)) - { - builder.Append(" metadata: "); - builder.AppendLine($"'{Metadata.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Parameters), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parameters: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Parameters)) - { - if (Parameters.Any()) - { - builder.Append(" parameters: "); - builder.AppendLine("{"); - foreach (var item in Parameters) - { - builder.Append($" '{item.Key}': "); - BicepSerializationHelpers.AppendChildObject(builder, item.Value, options, 6, false, " parameters: "); - } - builder.AppendLine(" }"); - } - } - } - - builder.AppendLine(" }"); - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PolicyDefinitionData)} does not support writing '{options.Format}' format."); - } - } - - PolicyDefinitionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicyDefinitionData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicyDefinitionData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyDefinitionData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyDefinitionData.cs deleted file mode 100644 index 6689f9af87..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicyDefinitionData.cs +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the PolicyDefinition data model. - /// The policy definition. - /// - public partial class PolicyDefinitionData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public PolicyDefinitionData() - { - Parameters = new ChangeTrackingDictionary(); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static. - /// The policy definition mode. Some examples are All, Indexed, Microsoft.KeyVault.Data. - /// The display name of the policy definition. - /// The policy definition description. - /// The policy rule. - /// The policy definition metadata. Metadata is an open ended object and is typically a collection of key value pairs. - /// The parameter definitions for parameters used in the policy rule. The keys are the parameter names. - /// Keeps track of any properties unknown to the library. - internal PolicyDefinitionData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, PolicyType? policyType, string mode, string displayName, string description, BinaryData policyRule, BinaryData metadata, IDictionary parameters, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - PolicyType = policyType; - Mode = mode; - DisplayName = displayName; - Description = description; - PolicyRule = policyRule; - Metadata = metadata; - Parameters = parameters; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static. - [WirePath("properties.policyType")] - public PolicyType? PolicyType { get; set; } - /// The policy definition mode. Some examples are All, Indexed, Microsoft.KeyVault.Data. - [WirePath("properties.mode")] - public string Mode { get; set; } - /// The display name of the policy definition. - [WirePath("properties.displayName")] - public string DisplayName { get; set; } - /// The policy definition description. - [WirePath("properties.description")] - public string Description { get; set; } - /// - /// The policy rule. - /// - /// To assign an object to this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("properties.policyRule")] - public BinaryData PolicyRule { get; set; } - /// - /// The policy definition metadata. Metadata is an open ended object and is typically a collection of key value pairs. - /// - /// To assign an object to this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("properties.metadata")] - public BinaryData Metadata { get; set; } - /// The parameter definitions for parameters used in the policy rule. The keys are the parameter names. - [WirePath("properties.parameters")] - public IDictionary Parameters { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicySetDefinitionData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicySetDefinitionData.Serialization.cs deleted file mode 100644 index f4122f7af1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicySetDefinitionData.Serialization.cs +++ /dev/null @@ -1,517 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class PolicySetDefinitionData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicySetDefinitionData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("properties"u8); - writer.WriteStartObject(); - if (Optional.IsDefined(PolicyType)) - { - writer.WritePropertyName("policyType"u8); - writer.WriteStringValue(PolicyType.Value.ToString()); - } - if (Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (Optional.IsDefined(Description)) - { - writer.WritePropertyName("description"u8); - writer.WriteStringValue(Description); - } - if (Optional.IsDefined(Metadata)) - { - writer.WritePropertyName("metadata"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(Metadata); -#else - using (JsonDocument document = JsonDocument.Parse(Metadata, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - if (Optional.IsCollectionDefined(Parameters)) - { - writer.WritePropertyName("parameters"u8); - writer.WriteStartObject(); - foreach (var item in Parameters) - { - writer.WritePropertyName(item.Key); - writer.WriteObjectValue(item.Value, options); - } - writer.WriteEndObject(); - } - if (Optional.IsCollectionDefined(PolicyDefinitions)) - { - writer.WritePropertyName("policyDefinitions"u8); - writer.WriteStartArray(); - foreach (var item in PolicyDefinitions) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(PolicyDefinitionGroups)) - { - writer.WritePropertyName("policyDefinitionGroups"u8); - writer.WriteStartArray(); - foreach (var item in PolicyDefinitionGroups) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - writer.WriteEndObject(); - } - - PolicySetDefinitionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PolicySetDefinitionData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePolicySetDefinitionData(document.RootElement, options); - } - - internal static PolicySetDefinitionData DeserializePolicySetDefinitionData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - PolicyType? policyType = default; - string displayName = default; - string description = default; - BinaryData metadata = default; - IDictionary parameters = default; - IList policyDefinitions = default; - IList policyDefinitionGroups = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - foreach (var property0 in property.Value.EnumerateObject()) - { - if (property0.NameEquals("policyType"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - policyType = new PolicyType(property0.Value.GetString()); - continue; - } - if (property0.NameEquals("displayName"u8)) - { - displayName = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("description"u8)) - { - description = property0.Value.GetString(); - continue; - } - if (property0.NameEquals("metadata"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - metadata = BinaryData.FromString(property0.Value.GetRawText()); - continue; - } - if (property0.NameEquals("parameters"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property1 in property0.Value.EnumerateObject()) - { - dictionary.Add(property1.Name, ArmPolicyParameter.DeserializeArmPolicyParameter(property1.Value, options)); - } - parameters = dictionary; - continue; - } - if (property0.NameEquals("policyDefinitions"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(PolicyDefinitionReference.DeserializePolicyDefinitionReference(item, options)); - } - policyDefinitions = array; - continue; - } - if (property0.NameEquals("policyDefinitionGroups"u8)) - { - if (property0.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property0.Value.EnumerateArray()) - { - array.Add(PolicyDefinitionGroup.DeserializePolicyDefinitionGroup(item, options)); - } - policyDefinitionGroups = array; - continue; - } - } - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PolicySetDefinitionData( - id, - name, - type, - systemData, - policyType, - displayName, - description, - metadata, - parameters ?? new ChangeTrackingDictionary(), - policyDefinitions ?? new ChangeTrackingList(), - policyDefinitionGroups ?? new ChangeTrackingList(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.Append(" properties:"); - builder.AppendLine(" {"); - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(PolicyType)) - { - builder.Append(" policyType: "); - builder.AppendLine($"'{PolicyType.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Description), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" description: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Description)) - { - builder.Append(" description: "); - if (Description.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Description}'''"); - } - else - { - builder.AppendLine($"'{Description}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Metadata), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" metadata: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Metadata)) - { - builder.Append(" metadata: "); - builder.AppendLine($"'{Metadata.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Parameters), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" parameters: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Parameters)) - { - if (Parameters.Any()) - { - builder.Append(" parameters: "); - builder.AppendLine("{"); - foreach (var item in Parameters) - { - builder.Append($" '{item.Key}': "); - BicepSerializationHelpers.AppendChildObject(builder, item.Value, options, 6, false, " parameters: "); - } - builder.AppendLine(" }"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyDefinitions), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyDefinitions: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(PolicyDefinitions)) - { - if (PolicyDefinitions.Any()) - { - builder.Append(" policyDefinitions: "); - builder.AppendLine("["); - foreach (var item in PolicyDefinitions) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 6, true, " policyDefinitions: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(PolicyDefinitionGroups), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" policyDefinitionGroups: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(PolicyDefinitionGroups)) - { - if (PolicyDefinitionGroups.Any()) - { - builder.Append(" policyDefinitionGroups: "); - builder.AppendLine("["); - foreach (var item in PolicyDefinitionGroups) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 6, true, " policyDefinitionGroups: "); - } - builder.AppendLine(" ]"); - } - } - } - - builder.AppendLine(" }"); - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(PolicySetDefinitionData)} does not support writing '{options.Format}' format."); - } - } - - PolicySetDefinitionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializePolicySetDefinitionData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PolicySetDefinitionData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicySetDefinitionData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicySetDefinitionData.cs deleted file mode 100644 index 22dae46c74..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/PolicySetDefinitionData.cs +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the PolicySetDefinition data model. - /// The policy set definition. - /// - public partial class PolicySetDefinitionData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - public PolicySetDefinitionData() - { - Parameters = new ChangeTrackingDictionary(); - PolicyDefinitions = new ChangeTrackingList(); - PolicyDefinitionGroups = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static. - /// The display name of the policy set definition. - /// The policy set definition description. - /// The policy set definition metadata. Metadata is an open ended object and is typically a collection of key value pairs. - /// The policy set definition parameters that can be used in policy definition references. - /// An array of policy definition references. - /// The metadata describing groups of policy definition references within the policy set definition. - /// Keeps track of any properties unknown to the library. - internal PolicySetDefinitionData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, PolicyType? policyType, string displayName, string description, BinaryData metadata, IDictionary parameters, IList policyDefinitions, IList policyDefinitionGroups, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - PolicyType = policyType; - DisplayName = displayName; - Description = description; - Metadata = metadata; - Parameters = parameters; - PolicyDefinitions = policyDefinitions; - PolicyDefinitionGroups = policyDefinitionGroups; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static. - [WirePath("properties.policyType")] - public PolicyType? PolicyType { get; set; } - /// The display name of the policy set definition. - [WirePath("properties.displayName")] - public string DisplayName { get; set; } - /// The policy set definition description. - [WirePath("properties.description")] - public string Description { get; set; } - /// - /// The policy set definition metadata. Metadata is an open ended object and is typically a collection of key value pairs. - /// - /// To assign an object to this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - [WirePath("properties.metadata")] - public BinaryData Metadata { get; set; } - /// The policy set definition parameters that can be used in policy definition references. - [WirePath("properties.parameters")] - public IDictionary Parameters { get; } - /// An array of policy definition references. - [WirePath("properties.policyDefinitions")] - public IList PolicyDefinitions { get; } - /// The metadata describing groups of policy definition references within the policy set definition. - [WirePath("properties.policyDefinitionGroups")] - public IList PolicyDefinitionGroups { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupCollection.cs deleted file mode 100644 index 6fa5910de7..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupCollection.cs +++ /dev/null @@ -1,500 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetResourceGroups method from an instance of . - /// - public partial class ResourceGroupCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _resourceGroupClientDiagnostics; - private readonly ResourceGroupsRestOperations _resourceGroupRestClient; - - /// Initializes a new instance of the class for mocking. - protected ResourceGroupCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal ResourceGroupCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _resourceGroupClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceGroupResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceGroupResource.ResourceType, out string resourceGroupApiVersion); - _resourceGroupRestClient = new ResourceGroupsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, resourceGroupApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != SubscriptionResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, SubscriptionResource.ResourceType), nameof(id)); - } - - /// - /// Creates or updates a resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the resource group to create or update. Can include alphanumeric, underscore, parentheses, hyphen, period (except at end), and Unicode characters that match the allowed characters. - /// Parameters supplied to the create or update a resource group. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string resourceGroupName, ResourceGroupData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _resourceGroupRestClient.CreateOrUpdateAsync(Id.SubscriptionId, resourceGroupName, data, cancellationToken).ConfigureAwait(false); - var uri = _resourceGroupRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, resourceGroupName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ResourceGroupResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Creates or updates a resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the resource group to create or update. Can include alphanumeric, underscore, parentheses, hyphen, period (except at end), and Unicode characters that match the allowed characters. - /// Parameters supplied to the create or update a resource group. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string resourceGroupName, ResourceGroupData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = _resourceGroupRestClient.CreateOrUpdate(Id.SubscriptionId, resourceGroupName, data, cancellationToken); - var uri = _resourceGroupRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, resourceGroupName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new ResourceGroupResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets a resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string resourceGroupName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupCollection.Get"); - scope.Start(); - try - { - var response = await _resourceGroupRestClient.GetAsync(Id.SubscriptionId, resourceGroupName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ResourceGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets a resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string resourceGroupName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupCollection.Get"); - scope.Start(); - try - { - var response = _resourceGroupRestClient.Get(Id.SubscriptionId, resourceGroupName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ResourceGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets all the resource groups for a subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups - /// - /// - /// Operation Id - /// ResourceGroups_List - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. - /// The number of results to return. If null is passed, returns all resource groups. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _resourceGroupRestClient.CreateListRequest(Id.SubscriptionId, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _resourceGroupRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new ResourceGroupResource(Client, ResourceGroupData.DeserializeResourceGroupData(e)), _resourceGroupClientDiagnostics, Pipeline, "ResourceGroupCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Gets all the resource groups for a subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups - /// - /// - /// Operation Id - /// ResourceGroups_List - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. - /// The number of results to return. If null is passed, returns all resource groups. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _resourceGroupRestClient.CreateListRequest(Id.SubscriptionId, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _resourceGroupRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new ResourceGroupResource(Client, ResourceGroupData.DeserializeResourceGroupData(e)), _resourceGroupClientDiagnostics, Pipeline, "ResourceGroupCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string resourceGroupName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupCollection.Exists"); - scope.Start(); - try - { - var response = await _resourceGroupRestClient.GetAsync(Id.SubscriptionId, resourceGroupName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string resourceGroupName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupCollection.Exists"); - scope.Start(); - try - { - var response = _resourceGroupRestClient.Get(Id.SubscriptionId, resourceGroupName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string resourceGroupName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _resourceGroupRestClient.GetAsync(Id.SubscriptionId, resourceGroupName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ResourceGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string resourceGroupName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupCollection.GetIfExists"); - scope.Start(); - try - { - var response = _resourceGroupRestClient.Get(Id.SubscriptionId, resourceGroupName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ResourceGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupData.Serialization.cs deleted file mode 100644 index 421513f67e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupData.Serialization.cs +++ /dev/null @@ -1,352 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class ResourceGroupData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - if (Optional.IsDefined(Properties)) - { - writer.WritePropertyName("properties"u8); - writer.WriteObjectValue(Properties, options); - } - if (Optional.IsDefined(ManagedBy)) - { - writer.WritePropertyName("managedBy"u8); - writer.WriteStringValue(ManagedBy); - } - } - - ResourceGroupData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceGroupData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceGroupData(document.RootElement, options); - } - - internal static ResourceGroupData DeserializeResourceGroupData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceGroupProperties properties = default; - string managedBy = default; - IDictionary tags = default; - AzureLocation location = default; - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("properties"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - properties = ResourceGroupProperties.DeserializeResourceGroupProperties(property.Value, options); - continue; - } - if (property.NameEquals("managedBy"u8)) - { - managedBy = property.Value.GetString(); - continue; - } - if (property.NameEquals("tags"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - tags = dictionary; - continue; - } - if (property.NameEquals("location"u8)) - { - location = new AzureLocation(property.Value.GetString()); - continue; - } - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceGroupData( - id, - name, - type, - systemData, - tags ?? new ChangeTrackingDictionary(), - location, - properties, - managedBy, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Location), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" location: "); - builder.AppendLine(propertyOverride); - } - else - { - builder.Append(" location: "); - builder.AppendLine($"'{Location.ToString()}'"); - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Tags), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tags: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Tags)) - { - if (Tags.Any()) - { - builder.Append(" tags: "); - builder.AppendLine("{"); - foreach (var item in Tags) - { - builder.Append($" '{item.Key}': "); - if (item.Value == null) - { - builder.Append("null"); - continue; - } - if (item.Value.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{item.Value}'''"); - } - else - { - builder.AppendLine($"'{item.Value}'"); - } - } - builder.AppendLine(" }"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue("ResourceGroupProvisioningState", out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" properties: "); - builder.AppendLine("{"); - builder.Append(" provisioningState: "); - builder.AppendLine(propertyOverride); - builder.AppendLine(" }"); - } - else - { - if (Optional.IsDefined(Properties)) - { - builder.Append(" properties: "); - BicepSerializationHelpers.AppendChildObject(builder, Properties, options, 2, false, " properties: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ManagedBy), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" managedBy: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ManagedBy)) - { - builder.Append(" managedBy: "); - if (ManagedBy.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{ManagedBy}'''"); - } - else - { - builder.AppendLine($"'{ManagedBy}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceGroupData)} does not support writing '{options.Format}' format."); - } - } - - ResourceGroupData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceGroupData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceGroupData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupData.cs deleted file mode 100644 index 86a684655c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupData.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the ResourceGroup data model. - /// Resource group information. - /// - public partial class ResourceGroupData : TrackedResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The location. - public ResourceGroupData(AzureLocation location) : base(location) - { - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The tags. - /// The location. - /// The resource group properties. - /// The ID of the resource that manages this resource group. - /// Keeps track of any properties unknown to the library. - internal ResourceGroupData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, IDictionary tags, AzureLocation location, ResourceGroupProperties properties, string managedBy, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData, tags, location) - { - Properties = properties; - ManagedBy = managedBy; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal ResourceGroupData() - { - } - - /// The resource group properties. - internal ResourceGroupProperties Properties { get; set; } - /// The provisioning state. - [WirePath("properties.provisioningState")] - public string ResourceGroupProvisioningState - { - get => Properties is null ? default : Properties.ProvisioningState; - } - - /// The ID of the resource that manages this resource group. - [WirePath("managedBy")] - public string ManagedBy { get; set; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupResource.Serialization.cs deleted file mode 100644 index 65a084b9bc..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class ResourceGroupResource : IJsonModel - { - private static ResourceGroupData s_dataDeserializationInstance; - private static ResourceGroupData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - ResourceGroupData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - ResourceGroupData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupResource.cs deleted file mode 100644 index 049966950d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceGroupResource.cs +++ /dev/null @@ -1,980 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a ResourceGroup along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetResourceGroupResource method. - /// Otherwise you can get one from its parent resource using the GetResourceGroup method. - /// - public partial class ResourceGroupResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The subscriptionId. - /// The resourceGroupName. - public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName) - { - var resourceId = $"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _resourceGroupClientDiagnostics; - private readonly ResourceGroupsRestOperations _resourceGroupRestClient; - private readonly ClientDiagnostics _resourceGroupResourcesClientDiagnostics; - private readonly ResourcesRestOperations _resourceGroupResourcesRestClient; - private readonly ResourceGroupData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Resources/resourceGroups"; - - /// Initializes a new instance of the class for mocking. - protected ResourceGroupResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal ResourceGroupResource(ArmClient client, ResourceGroupData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal ResourceGroupResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _resourceGroupClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string resourceGroupApiVersion); - _resourceGroupRestClient = new ResourceGroupsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, resourceGroupApiVersion); - _resourceGroupResourcesClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string resourceGroupResourcesApiVersion); - _resourceGroupResourcesRestClient = new ResourcesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, resourceGroupResourcesApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual ResourceGroupData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// Gets a resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.Get"); - scope.Start(); - try - { - var response = await _resourceGroupRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ResourceGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets a resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.Get"); - scope.Start(); - try - { - var response = _resourceGroupRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ResourceGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// When you delete a resource group, all of its resources are also deleted. Deleting a resource group deletes all of its template deployments and currently stored operations. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Delete - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The resource types you want to force delete. Currently, only the following is supported: forceDeletionTypes=Microsoft.Compute/virtualMachines,Microsoft.Compute/virtualMachineScaleSets. - /// The cancellation token to use. - public virtual async Task DeleteAsync(WaitUntil waitUntil, string forceDeletionTypes = null, CancellationToken cancellationToken = default) - { - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.Delete"); - scope.Start(); - try - { - var response = await _resourceGroupRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, forceDeletionTypes, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(_resourceGroupClientDiagnostics, Pipeline, _resourceGroupRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, forceDeletionTypes).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// When you delete a resource group, all of its resources are also deleted. Deleting a resource group deletes all of its template deployments and currently stored operations. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Delete - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The resource types you want to force delete. Currently, only the following is supported: forceDeletionTypes=Microsoft.Compute/virtualMachines,Microsoft.Compute/virtualMachineScaleSets. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, string forceDeletionTypes = null, CancellationToken cancellationToken = default) - { - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.Delete"); - scope.Start(); - try - { - var response = _resourceGroupRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, forceDeletionTypes, cancellationToken); - var operation = new ResourcesArmOperation(_resourceGroupClientDiagnostics, Pipeline, _resourceGroupRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, forceDeletionTypes).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Resource groups can be updated through a simple PATCH operation to a group address. The format of the request is the same as that for creating a resource group. If a field is unspecified, the current value is retained. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Update - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Parameters supplied to update a resource group. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(ResourceGroupPatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(patch, nameof(patch)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.Update"); - scope.Start(); - try - { - var response = await _resourceGroupRestClient.UpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, patch, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new ResourceGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Resource groups can be updated through a simple PATCH operation to a group address. The format of the request is the same as that for creating a resource group. If a field is unspecified, the current value is retained. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Update - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Parameters supplied to update a resource group. - /// The cancellation token to use. - /// is null. - public virtual Response Update(ResourceGroupPatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(patch, nameof(patch)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.Update"); - scope.Start(); - try - { - var response = _resourceGroupRestClient.Update(Id.SubscriptionId, Id.ResourceGroupName, patch, cancellationToken); - return Response.FromValue(new ResourceGroupResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// The resources to be moved must be in the same source resource group in the source subscription being used. The target resource group may be in a different subscription. When moving resources, both the source group and the target group are locked for the duration of the operation. Write and delete operations are blocked on the groups until the move completes. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourceGroups/{sourceResourceGroupName}/moveResources - /// - /// - /// Operation Id - /// Resources_MoveResources - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Parameters for moving resources. - /// The cancellation token to use. - /// is null. - public virtual async Task MoveResourcesAsync(WaitUntil waitUntil, ResourcesMoveContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = _resourceGroupResourcesClientDiagnostics.CreateScope("ResourceGroupResource.MoveResources"); - scope.Start(); - try - { - var response = await _resourceGroupResourcesRestClient.MoveResourcesAsync(Id.SubscriptionId, Id.ResourceGroupName, content, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(_resourceGroupResourcesClientDiagnostics, Pipeline, _resourceGroupResourcesRestClient.CreateMoveResourcesRequest(Id.SubscriptionId, Id.ResourceGroupName, content).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// The resources to be moved must be in the same source resource group in the source subscription being used. The target resource group may be in a different subscription. When moving resources, both the source group and the target group are locked for the duration of the operation. Write and delete operations are blocked on the groups until the move completes. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourceGroups/{sourceResourceGroupName}/moveResources - /// - /// - /// Operation Id - /// Resources_MoveResources - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Parameters for moving resources. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation MoveResources(WaitUntil waitUntil, ResourcesMoveContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = _resourceGroupResourcesClientDiagnostics.CreateScope("ResourceGroupResource.MoveResources"); - scope.Start(); - try - { - var response = _resourceGroupResourcesRestClient.MoveResources(Id.SubscriptionId, Id.ResourceGroupName, content, cancellationToken); - var operation = new ResourcesArmOperation(_resourceGroupResourcesClientDiagnostics, Pipeline, _resourceGroupResourcesRestClient.CreateMoveResourcesRequest(Id.SubscriptionId, Id.ResourceGroupName, content).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation checks whether the specified resources can be moved to the target. The resources to be moved must be in the same source resource group in the source subscription being used. The target resource group may be in a different subscription. If validation succeeds, it returns HTTP response code 204 (no content). If validation fails, it returns HTTP response code 409 (Conflict) with an error message. Retrieve the URL in the Location header value to check the result of the long-running operation. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourceGroups/{sourceResourceGroupName}/validateMoveResources - /// - /// - /// Operation Id - /// Resources_ValidateMoveResources - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Parameters for moving resources. - /// The cancellation token to use. - /// is null. - public virtual async Task ValidateMoveResourcesAsync(WaitUntil waitUntil, ResourcesMoveContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = _resourceGroupResourcesClientDiagnostics.CreateScope("ResourceGroupResource.ValidateMoveResources"); - scope.Start(); - try - { - var response = await _resourceGroupResourcesRestClient.ValidateMoveResourcesAsync(Id.SubscriptionId, Id.ResourceGroupName, content, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(_resourceGroupResourcesClientDiagnostics, Pipeline, _resourceGroupResourcesRestClient.CreateValidateMoveResourcesRequest(Id.SubscriptionId, Id.ResourceGroupName, content).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation checks whether the specified resources can be moved to the target. The resources to be moved must be in the same source resource group in the source subscription being used. The target resource group may be in a different subscription. If validation succeeds, it returns HTTP response code 204 (no content). If validation fails, it returns HTTP response code 409 (Conflict) with an error message. Retrieve the URL in the Location header value to check the result of the long-running operation. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourceGroups/{sourceResourceGroupName}/validateMoveResources - /// - /// - /// Operation Id - /// Resources_ValidateMoveResources - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Parameters for moving resources. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation ValidateMoveResources(WaitUntil waitUntil, ResourcesMoveContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = _resourceGroupResourcesClientDiagnostics.CreateScope("ResourceGroupResource.ValidateMoveResources"); - scope.Start(); - try - { - var response = _resourceGroupResourcesRestClient.ValidateMoveResources(Id.SubscriptionId, Id.ResourceGroupName, content, cancellationToken); - var operation = new ResourcesArmOperation(_resourceGroupResourcesClientDiagnostics, Pipeline, _resourceGroupResourcesRestClient.CreateValidateMoveResourcesRequest(Id.SubscriptionId, Id.ResourceGroupName, content).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Captures the specified resource group as a template. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/exportTemplate - /// - /// - /// Operation Id - /// ResourceGroups_ExportTemplate - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Parameters for exporting the template. - /// The cancellation token to use. - /// is null. - public virtual async Task> ExportTemplateAsync(WaitUntil waitUntil, ExportTemplate exportTemplate, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(exportTemplate, nameof(exportTemplate)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.ExportTemplate"); - scope.Start(); - try - { - var response = await _resourceGroupRestClient.ExportTemplateAsync(Id.SubscriptionId, Id.ResourceGroupName, exportTemplate, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(new ResourceGroupExportResultOperationSource(), _resourceGroupClientDiagnostics, Pipeline, _resourceGroupRestClient.CreateExportTemplateRequest(Id.SubscriptionId, Id.ResourceGroupName, exportTemplate).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Captures the specified resource group as a template. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/exportTemplate - /// - /// - /// Operation Id - /// ResourceGroups_ExportTemplate - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// Parameters for exporting the template. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation ExportTemplate(WaitUntil waitUntil, ExportTemplate exportTemplate, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(exportTemplate, nameof(exportTemplate)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.ExportTemplate"); - scope.Start(); - try - { - var response = _resourceGroupRestClient.ExportTemplate(Id.SubscriptionId, Id.ResourceGroupName, exportTemplate, cancellationToken); - var operation = new ResourcesArmOperation(new ResourceGroupExportResultOperationSource(), _resourceGroupClientDiagnostics, Pipeline, _resourceGroupRestClient.CreateExportTemplateRequest(Id.SubscriptionId, Id.ResourceGroupName, exportTemplate).Request, response, OperationFinalStateVia.Location); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Add a tag to the current resource. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The key for the tag. - /// The value for the tag. - /// The cancellation token to use. - /// or is null. - public virtual async Task> AddTagAsync(string key, string value, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(key, nameof(key)); - Argument.AssertNotNull(value, nameof(value)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.AddTag"); - scope.Start(); - try - { - if (await CanUseTagResourceAsync(cancellationToken: cancellationToken).ConfigureAwait(false)) - { - var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false); - originalTags.Value.Data.TagValues[key] = value; - await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false); - var originalResponse = await _resourceGroupRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new ResourceGroupResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - else - { - var current = (await GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false)).Value.Data; - var patch = new ResourceGroupPatch(); - foreach (var tag in current.Tags) - { - patch.Tags.Add(tag); - } - patch.Tags[key] = value; - var result = await UpdateAsync(patch, cancellationToken: cancellationToken).ConfigureAwait(false); - return result; - } - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Add a tag to the current resource. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The key for the tag. - /// The value for the tag. - /// The cancellation token to use. - /// or is null. - public virtual Response AddTag(string key, string value, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(key, nameof(key)); - Argument.AssertNotNull(value, nameof(value)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.AddTag"); - scope.Start(); - try - { - if (CanUseTagResource(cancellationToken: cancellationToken)) - { - var originalTags = GetTagResource().Get(cancellationToken); - originalTags.Value.Data.TagValues[key] = value; - GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken); - var originalResponse = _resourceGroupRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken); - return Response.FromValue(new ResourceGroupResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - else - { - var current = Get(cancellationToken: cancellationToken).Value.Data; - var patch = new ResourceGroupPatch(); - foreach (var tag in current.Tags) - { - patch.Tags.Add(tag); - } - patch.Tags[key] = value; - var result = Update(patch, cancellationToken: cancellationToken); - return result; - } - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Replace the tags on the resource with the given set. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The set of tags to use as replacement. - /// The cancellation token to use. - /// is null. - public virtual async Task> SetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(tags, nameof(tags)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.SetTags"); - scope.Start(); - try - { - if (await CanUseTagResourceAsync(cancellationToken: cancellationToken).ConfigureAwait(false)) - { - await GetTagResource().DeleteAsync(WaitUntil.Completed, cancellationToken: cancellationToken).ConfigureAwait(false); - var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false); - originalTags.Value.Data.TagValues.ReplaceWith(tags); - await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false); - var originalResponse = await _resourceGroupRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new ResourceGroupResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - else - { - var current = (await GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false)).Value.Data; - var patch = new ResourceGroupPatch(); - patch.Tags.ReplaceWith(tags); - var result = await UpdateAsync(patch, cancellationToken: cancellationToken).ConfigureAwait(false); - return result; - } - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Replace the tags on the resource with the given set. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The set of tags to use as replacement. - /// The cancellation token to use. - /// is null. - public virtual Response SetTags(IDictionary tags, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(tags, nameof(tags)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.SetTags"); - scope.Start(); - try - { - if (CanUseTagResource(cancellationToken: cancellationToken)) - { - GetTagResource().Delete(WaitUntil.Completed, cancellationToken: cancellationToken); - var originalTags = GetTagResource().Get(cancellationToken); - originalTags.Value.Data.TagValues.ReplaceWith(tags); - GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken); - var originalResponse = _resourceGroupRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken); - return Response.FromValue(new ResourceGroupResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - else - { - var current = Get(cancellationToken: cancellationToken).Value.Data; - var patch = new ResourceGroupPatch(); - patch.Tags.ReplaceWith(tags); - var result = Update(patch, cancellationToken: cancellationToken); - return result; - } - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Removes a tag by key from the resource. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The key for the tag. - /// The cancellation token to use. - /// is null. - public virtual async Task> RemoveTagAsync(string key, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(key, nameof(key)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.RemoveTag"); - scope.Start(); - try - { - if (await CanUseTagResourceAsync(cancellationToken: cancellationToken).ConfigureAwait(false)) - { - var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false); - originalTags.Value.Data.TagValues.Remove(key); - await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false); - var originalResponse = await _resourceGroupRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new ResourceGroupResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - else - { - var current = (await GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false)).Value.Data; - var patch = new ResourceGroupPatch(); - foreach (var tag in current.Tags) - { - patch.Tags.Add(tag); - } - patch.Tags.Remove(key); - var result = await UpdateAsync(patch, cancellationToken: cancellationToken).ConfigureAwait(false); - return result; - } - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Removes a tag by key from the resource. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The key for the tag. - /// The cancellation token to use. - /// is null. - public virtual Response RemoveTag(string key, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(key, nameof(key)); - - using var scope = _resourceGroupClientDiagnostics.CreateScope("ResourceGroupResource.RemoveTag"); - scope.Start(); - try - { - if (CanUseTagResource(cancellationToken: cancellationToken)) - { - var originalTags = GetTagResource().Get(cancellationToken); - originalTags.Value.Data.TagValues.Remove(key); - GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken); - var originalResponse = _resourceGroupRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken); - return Response.FromValue(new ResourceGroupResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); - } - else - { - var current = Get(cancellationToken: cancellationToken).Value.Data; - var patch = new ResourceGroupPatch(); - foreach (var tag in current.Tags) - { - patch.Tags.Add(tag); - } - patch.Tags.Remove(key); - var result = Update(patch, cancellationToken: cancellationToken); - return result; - } - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceManagerModelFactory.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceManagerModelFactory.cs deleted file mode 100644 index c17962de61..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceManagerModelFactory.cs +++ /dev/null @@ -1,764 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Linq; -using Azure.Core; -using Azure.ResourceManager.Resources; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Models -{ - /// Model factory for models. - public static partial class ResourceManagerModelFactory - { - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The location of the policy assignment. Only required when utilizing managed identity. - /// The managed identity associated with the policy assignment. Current supported identity types: None, SystemAssigned, UserAssigned. - /// The display name of the policy assignment. - /// The ID of the policy definition or policy set definition being assigned. - /// The scope for the policy assignment. - /// The policy's excluded scopes. - /// The parameter values for the assigned policy rule. The keys are the parameter names. - /// This message will be part of response in case of policy violation. - /// The policy assignment metadata. Metadata is an open ended object and is typically a collection of key value pairs. - /// The policy assignment enforcement mode. Possible values are Default and DoNotEnforce. - /// The messages that describe why a resource is non-compliant with the policy. - /// The resource selector list to filter policies by resource properties. - /// The policy property value override. - /// A new instance for mocking. - public static PolicyAssignmentData PolicyAssignmentData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, AzureLocation? location = null, ManagedServiceIdentity managedIdentity = null, string displayName = null, string policyDefinitionId = null, string scope = null, IEnumerable excludedScopes = null, IDictionary parameters = null, string description = null, BinaryData metadata = null, EnforcementMode? enforcementMode = null, IEnumerable nonComplianceMessages = null, IEnumerable resourceSelectors = null, IEnumerable overrides = null) - { - excludedScopes ??= new List(); - parameters ??= new Dictionary(); - nonComplianceMessages ??= new List(); - resourceSelectors ??= new List(); - overrides ??= new List(); - - return new PolicyAssignmentData( - id, - name, - resourceType, - systemData, - location, - managedIdentity, - displayName, - policyDefinitionId, - scope, - excludedScopes?.ToList(), - parameters, - description, - metadata, - enforcementMode, - nonComplianceMessages?.ToList(), - resourceSelectors?.ToList(), - overrides?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static. - /// The policy definition mode. Some examples are All, Indexed, Microsoft.KeyVault.Data. - /// The display name of the policy definition. - /// The policy definition description. - /// The policy rule. - /// The policy definition metadata. Metadata is an open ended object and is typically a collection of key value pairs. - /// The parameter definitions for parameters used in the policy rule. The keys are the parameter names. - /// A new instance for mocking. - public static PolicyDefinitionData PolicyDefinitionData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, PolicyType? policyType = null, string mode = null, string displayName = null, string description = null, BinaryData policyRule = null, BinaryData metadata = null, IDictionary parameters = null) - { - parameters ??= new Dictionary(); - - return new PolicyDefinitionData( - id, - name, - resourceType, - systemData, - policyType, - mode, - displayName, - description, - policyRule, - metadata, - parameters, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The type of policy definition. Possible values are NotSpecified, BuiltIn, Custom, and Static. - /// The display name of the policy set definition. - /// The policy set definition description. - /// The policy set definition metadata. Metadata is an open ended object and is typically a collection of key value pairs. - /// The policy set definition parameters that can be used in policy definition references. - /// An array of policy definition references. - /// The metadata describing groups of policy definition references within the policy set definition. - /// A new instance for mocking. - public static PolicySetDefinitionData PolicySetDefinitionData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, PolicyType? policyType = null, string displayName = null, string description = null, BinaryData metadata = null, IDictionary parameters = null, IEnumerable policyDefinitions = null, IEnumerable policyDefinitionGroups = null) - { - parameters ??= new Dictionary(); - policyDefinitions ??= new List(); - policyDefinitionGroups ??= new List(); - - return new PolicySetDefinitionData( - id, - name, - resourceType, - systemData, - policyType, - displayName, - description, - metadata, - parameters, - policyDefinitions?.ToList(), - policyDefinitionGroups?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The list of namespaces for the data policy manifest. - /// The policy mode of the data policy manifest. - /// A value indicating whether policy mode is allowed only in built-in definitions. - /// An array of resource type aliases. - /// The effect definition. - /// The non-alias field accessor values that can be used in the policy rule. - /// The standard resource functions (subscription and/or resourceGroup). - /// An array of data manifest custom resource definition. - /// A new instance for mocking. - public static DataPolicyManifestData DataPolicyManifestData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, IEnumerable namespaces = null, string policyMode = null, bool? isBuiltInOnly = null, IEnumerable resourceTypeAliases = null, IEnumerable effects = null, IEnumerable fieldValues = null, IEnumerable standard = null, IEnumerable customDefinitions = null) - { - namespaces ??= new List(); - resourceTypeAliases ??= new List(); - effects ??= new List(); - fieldValues ??= new List(); - standard ??= new List(); - customDefinitions ??= new List(); - - return new DataPolicyManifestData( - id, - name, - resourceType, - systemData, - namespaces?.ToList(), - policyMode, - isBuiltInOnly, - resourceTypeAliases?.ToList(), - effects?.ToList(), - fieldValues?.ToList(), - standard?.ToList(), - customDefinitions?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The resource type name. - /// The aliases for property names. - /// A new instance for mocking. - public static ResourceTypeAliases ResourceTypeAliases(string resourceType = null, IEnumerable aliases = null) - { - aliases ??= new List(); - - return new ResourceTypeAliases(resourceType, aliases?.ToList(), serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The alias name. - /// The paths for an alias. - /// The type of the alias. - /// The default path for an alias. - /// The default pattern for an alias. - /// The default alias path metadata. Applies to the default path and to any alias path that doesn't have metadata. - /// A new instance for mocking. - public static ResourceTypeAlias ResourceTypeAlias(string name = null, IEnumerable paths = null, ResourceTypeAliasType? aliasType = null, string defaultPath = null, ResourceTypeAliasPattern defaultPattern = null, ResourceTypeAliasPathMetadata defaultMetadata = null) - { - paths ??= new List(); - - return new ResourceTypeAlias( - name, - paths?.ToList(), - aliasType, - defaultPath, - defaultPattern, - defaultMetadata, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The path of an alias. - /// The API versions. - /// The pattern for an alias path. - /// The metadata of the alias path. If missing, fall back to the default metadata of the alias. - /// A new instance for mocking. - public static ResourceTypeAliasPath ResourceTypeAliasPath(string path = null, IEnumerable apiVersions = null, ResourceTypeAliasPattern pattern = null, ResourceTypeAliasPathMetadata metadata = null) - { - apiVersions ??= new List(); - - return new ResourceTypeAliasPath(path, apiVersions?.ToList(), pattern, metadata, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The alias pattern phrase. - /// The alias pattern variable. - /// The type of alias pattern. - /// A new instance for mocking. - public static ResourceTypeAliasPattern ResourceTypeAliasPattern(string phrase = null, string variable = null, ResourceTypeAliasPatternType? patternType = null) - { - return new ResourceTypeAliasPattern(phrase, variable, patternType, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The type of the token that the alias path is referring to. - /// The attributes of the token that the alias path is referring to. - /// A new instance for mocking. - public static ResourceTypeAliasPathMetadata ResourceTypeAliasPathMetadata(ResourceTypeAliasPathTokenType? tokenType = null, ResourceTypeAliasPathAttributes? attributes = null) - { - return new ResourceTypeAliasPathMetadata(tokenType, attributes, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The data effect name. - /// The data effect details schema. - /// A new instance for mocking. - public static DataPolicyManifestEffect DataPolicyManifestEffect(string name = null, BinaryData detailsSchema = null) - { - return new DataPolicyManifestEffect(name, detailsSchema, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The function name as it will appear in the policy rule. eg - 'vault'. - /// The fully qualified control plane resource type that this function represents. eg - 'Microsoft.KeyVault/vaults'. - /// The top-level properties that can be selected on the function's output. eg - [ "name", "location" ] if vault().name and vault().location are supported. - /// A value indicating whether the custom properties within the property bag are allowed. Needs api-version to be specified in the policy rule eg - vault('2019-06-01'). - /// A new instance for mocking. - public static DataManifestCustomResourceFunctionDefinition DataManifestCustomResourceFunctionDefinition(string name = null, ResourceType? fullyQualifiedResourceType = null, IEnumerable defaultProperties = null, bool? allowCustomProperties = null) - { - defaultProperties ??= new List(); - - return new DataManifestCustomResourceFunctionDefinition(name, fullyQualifiedResourceType, defaultProperties?.ToList(), allowCustomProperties, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The level of the lock. Possible values are: NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users are able to read and modify the resources, but not delete. ReadOnly means authorized users can only read from a resource, but they can't modify or delete it. - /// Notes about the lock. Maximum of 512 characters. - /// The owners of the lock. - /// A new instance for mocking. - public static ManagementLockData ManagementLockData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, ManagementLockLevel level = default, string notes = null, IEnumerable owners = null) - { - owners ??= new List(); - - return new ManagementLockData( - id, - name, - resourceType, - systemData, - level, - notes, - owners?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The provider ID. - /// The namespace of the resource provider. - /// The registration state of the resource provider. - /// The registration policy of the resource provider. - /// The collection of provider resource types. - /// The provider authorization consent state. - /// A new instance for mocking. - public static ResourceProviderData ResourceProviderData(ResourceIdentifier id = null, string @namespace = null, string registrationState = null, string registrationPolicy = null, IEnumerable resourceTypes = null, ProviderAuthorizationConsentState? providerAuthorizationConsentState = null) - { - resourceTypes ??= new List(); - - return new ResourceProviderData( - id, - @namespace, - registrationState, - registrationPolicy, - resourceTypes?.ToList(), - providerAuthorizationConsentState, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The resource type. - /// The collection of locations where this resource type can be created. - /// The location mappings that are supported by this resource type. - /// The aliases that are supported by this resource type. - /// The API version. - /// The default API version. - /// - /// The API profiles for the resource provider. - /// The additional capabilities offered by this resource type. - /// The properties. - /// A new instance for mocking. - public static ProviderResourceType ProviderResourceType(string resourceType = null, IEnumerable locations = null, IEnumerable locationMappings = null, IEnumerable aliases = null, IEnumerable apiVersions = null, string defaultApiVersion = null, IEnumerable zoneMappings = null, IEnumerable apiProfiles = null, string capabilities = null, IReadOnlyDictionary properties = null) - { - locations ??= new List(); - locationMappings ??= new List(); - aliases ??= new List(); - apiVersions ??= new List(); - zoneMappings ??= new List(); - apiProfiles ??= new List(); - properties ??= new Dictionary(); - - return new ProviderResourceType( - resourceType, - locations?.ToList(), - locationMappings?.ToList(), - aliases?.ToList(), - apiVersions?.ToList(), - defaultApiVersion, - zoneMappings?.ToList(), - apiProfiles?.ToList(), - capabilities, - properties, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The azure location. - /// The extended location type. - /// The extended locations for the azure location. - /// A new instance for mocking. - public static ProviderExtendedLocation ProviderExtendedLocation(AzureLocation? location = null, string providerExtendedLocationType = null, IEnumerable extendedLocations = null) - { - extendedLocations ??= new List(); - - return new ProviderExtendedLocation(location, providerExtendedLocationType, extendedLocations?.ToList(), serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The location of the zone mapping. - /// - /// A new instance for mocking. - public static ZoneMapping ZoneMapping(AzureLocation? location = null, IEnumerable zones = null) - { - zones ??= new List(); - - return new ZoneMapping(location, zones?.ToList(), serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The profile version. - /// The API version. - /// A new instance for mocking. - public static ApiProfile ApiProfile(string profileVersion = null, string apiVersion = null) - { - return new ApiProfile(profileVersion, apiVersion, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The application id. - /// Role definition properties. - /// Role definition properties. - /// The provider authorization consent state. - /// A new instance for mocking. - public static ProviderPermission ProviderPermission(string applicationId = null, AzureRoleDefinition roleDefinition = null, AzureRoleDefinition managedByRoleDefinition = null, ProviderAuthorizationConsentState? providerAuthorizationConsentState = null) - { - return new ProviderPermission(applicationId, roleDefinition, managedByRoleDefinition, providerAuthorizationConsentState, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The role definition ID. - /// The role definition name. - /// If this is a service role. - /// Role definition permissions. - /// Role definition assignable scopes. - /// A new instance for mocking. - public static AzureRoleDefinition AzureRoleDefinition(string id = null, string name = null, bool? isServiceRole = null, IEnumerable permissions = null, IEnumerable scopes = null) - { - permissions ??= new List(); - scopes ??= new List(); - - return new AzureRoleDefinition( - id, - name, - isServiceRole, - permissions?.ToList(), - scopes?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// Allowed actions. - /// Denied actions. - /// Allowed Data actions. - /// Denied Data actions. - /// A new instance for mocking. - public static Permission Permission(IEnumerable allowedActions = null, IEnumerable deniedActions = null, IEnumerable allowedDataActions = null, IEnumerable deniedDataActions = null) - { - allowedActions ??= new List(); - deniedActions ??= new List(); - allowedDataActions ??= new List(); - deniedDataActions ??= new List(); - - return new Permission(allowedActions?.ToList(), deniedActions?.ToList(), allowedDataActions?.ToList(), deniedDataActions?.ToList(), serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The namespace of the resource provider. - /// The collection of provider resource types. - /// A new instance for mocking. - public static TenantResourceProvider TenantResourceProvider(string @namespace = null, IEnumerable resourceTypes = null) - { - resourceTypes ??= new List(); - - return new TenantResourceProvider(@namespace, resourceTypes?.ToList(), serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The tags. - /// The location. - /// Resource extended location. - /// The plan of the resource. - /// The resource properties. - /// The kind of the resource. - /// ID of the resource that manages this resource. - /// The SKU of the resource. - /// The identity of the resource. - /// The created time of the resource. This is only present if requested via the $expand query parameter. - /// The changed time of the resource. This is only present if requested via the $expand query parameter. - /// The provisioning state of the resource. This is only present if requested via the $expand query parameter. - /// A new instance for mocking. - public static GenericResourceData GenericResourceData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, IDictionary tags = null, AzureLocation location = default, ExtendedLocation extendedLocation = null, ArmPlan plan = null, BinaryData properties = null, string kind = null, string managedBy = null, ResourcesSku sku = null, ManagedServiceIdentity identity = null, DateTimeOffset? createdOn = null, DateTimeOffset? changedOn = null, string provisioningState = null) - { - tags ??= new Dictionary(); - - return new GenericResourceData( - id, - name, - resourceType, - systemData, - tags, - location, - extendedLocation, - serializedAdditionalRawData: null, - plan, - properties, - kind, - managedBy, - sku, - identity, - createdOn, - changedOn, - provisioningState); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The tags. - /// The location. - /// Resource extended location. - /// A new instance for mocking. - public static TrackedResourceExtendedData TrackedResourceExtendedData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, IDictionary tags = null, AzureLocation location = default, ExtendedLocation extendedLocation = null) - { - tags ??= new Dictionary(); - - return new TrackedResourceExtendedData( - id, - name, - resourceType, - systemData, - tags, - location, - extendedLocation, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The tags. - /// The location. - /// The resource group properties. - /// The ID of the resource that manages this resource group. - /// A new instance for mocking. - public static ResourceGroupData ResourceGroupData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, IDictionary tags = null, AzureLocation location = default, string resourceGroupProvisioningState = null, string managedBy = null) - { - tags ??= new Dictionary(); - - return new ResourceGroupData( - id, - name, - resourceType, - systemData, - tags, - location, - resourceGroupProvisioningState != null ? new ResourceGroupProperties(resourceGroupProvisioningState, serializedAdditionalRawData: null) : null, - managedBy, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The template content. - /// The template export error. - /// A new instance for mocking. - public static ResourceGroupExportResult ResourceGroupExportResult(BinaryData template = null, ResponseError error = null) - { - return new ResourceGroupExportResult(template, error, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The tag value ID. - /// The tag value. - /// The tag value count. - /// A new instance for mocking. - public static PredefinedTagValue PredefinedTagValue(string id = null, string tagValue = null, PredefinedTagCount count = null) - { - return new PredefinedTagValue(id, tagValue, count, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// Type of count. - /// Value of count. - /// A new instance for mocking. - public static PredefinedTagCount PredefinedTagCount(string predefinedTagCountType = null, int? value = null) - { - return new PredefinedTagCount(predefinedTagCountType, value, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The tag name ID. - /// The tag name. - /// The total number of resources that use the resource tag. When a tag is initially created and has no associated resources, the value is 0. - /// The list of tag values. - /// A new instance for mocking. - public static PredefinedTag PredefinedTag(string id = null, string tagName = null, PredefinedTagCount count = null, IEnumerable values = null) - { - values ??= new List(); - - return new PredefinedTag(id, tagName, count, values?.ToList(), serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The set of tags. - /// A new instance for mocking. - public static TagResourceData TagResourceData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, IDictionary tagValues = null) - { - tagValues ??= new Dictionary(); - - return new TagResourceData( - id, - name, - resourceType, - systemData, - tagValues != null ? new Tag(tagValues, serializedAdditionalRawData: null) : null, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The fully qualified ID of the location. For example, /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74/locations/westus. - /// The subscription ID. - /// The location name. - /// The location type. - /// The display name of the location. - /// The display name of the location and its region. - /// Metadata of the location, such as lat/long, paired region, and others. - /// The availability zone mappings for this region. - /// A new instance for mocking. - public static LocationExpanded LocationExpanded(string id = null, string subscriptionId = null, string name = null, LocationType? locationType = null, string displayName = null, string regionalDisplayName = null, LocationMetadata metadata = null, IEnumerable availabilityZoneMappings = null) - { - availabilityZoneMappings ??= new List(); - - return new LocationExpanded( - id, - subscriptionId, - name, - locationType, - displayName, - regionalDisplayName, - metadata, - availabilityZoneMappings?.ToList(), - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The type of the region. - /// The category of the region. - /// The geography of the location. - /// The geography group of the location. - /// The longitude of the location. - /// The latitude of the location. - /// The physical location of the Azure location. - /// The regions paired to this region. - /// The home location of an edge zone. - /// A new instance for mocking. - public static LocationMetadata LocationMetadata(RegionType? regionType = null, RegionCategory? regionCategory = null, string geography = null, string geographyGroup = null, double? longitude = null, double? latitude = null, string physicalLocation = null, IEnumerable pairedRegions = null, string homeLocation = null) - { - pairedRegions ??= new List(); - - return new LocationMetadata( - regionType, - regionCategory, - geography, - geographyGroup, - longitude, - latitude, - physicalLocation, - pairedRegions?.ToList(), - homeLocation, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The name of the paired region. - /// The fully qualified ID of the location. For example, /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74/locations/westus. - /// The subscription ID. - /// A new instance for mocking. - public static PairedRegion PairedRegion(string name = null, string id = null, string subscriptionId = null) - { - return new PairedRegion(name, id, subscriptionId, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The logical zone id for the availability zone. - /// The fully qualified physical zone id of availability zone to which logical zone id is mapped to. - /// A new instance for mocking. - public static AvailabilityZoneMappings AvailabilityZoneMappings(string logicalZone = null, string physicalZone = null) - { - return new AvailabilityZoneMappings(logicalZone, physicalZone, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The fully qualified ID for the subscription. For example, /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74. - /// The subscription ID. - /// The subscription display name. - /// The subscription tenant ID. - /// The subscription state. Possible values are Enabled, Warned, PastDue, Disabled, and Deleted. - /// The subscription policies. - /// The authorization source of the request. Valid values are one or more combinations of Legacy, RoleBased, Bypassed, Direct and Management. For example, 'Legacy, RoleBased'. - /// An array containing the tenants managing the subscription. - /// The tags attached to the subscription. - /// A new instance for mocking. - public static SubscriptionData SubscriptionData(ResourceIdentifier id = null, string subscriptionId = null, string displayName = null, Guid? tenantId = null, SubscriptionState? state = null, SubscriptionPolicies subscriptionPolicies = null, string authorizationSource = null, IEnumerable managedByTenants = null, IReadOnlyDictionary tags = null) - { - managedByTenants ??= new List(); - tags ??= new Dictionary(); - - return new SubscriptionData( - id, - subscriptionId, - displayName, - tenantId, - state, - subscriptionPolicies, - authorizationSource, - managedByTenants?.ToList(), - tags, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The subscription location placement ID. The ID indicates which regions are visible for a subscription. For example, a subscription with a location placement Id of Public_2014-09-01 has access to Azure public regions. - /// The subscription quota ID. - /// The subscription spending limit. - /// A new instance for mocking. - public static SubscriptionPolicies SubscriptionPolicies(string locationPlacementId = null, string quotaId = null, SpendingLimit? spendingLimit = null) - { - return new SubscriptionPolicies(locationPlacementId, quotaId, spendingLimit, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The tenant ID of the managing tenant. This is a GUID. - /// A new instance for mocking. - public static ManagedByTenant ManagedByTenant(Guid? tenantId = null) - { - return new ManagedByTenant(tenantId, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The fully qualified ID of the tenant. For example, /tenants/8d65815f-a5b6-402f-9298-045155da7d74. - /// The tenant ID. For example, 8d65815f-a5b6-402f-9298-045155da7d74. - /// Category of the tenant. - /// Country/region name of the address for the tenant. - /// Country/region abbreviation for the tenant. - /// The display name of the tenant. - /// The list of domains for the tenant. - /// The default domain for the tenant. - /// The tenant type. Only available for 'Home' tenant category. - /// The tenant's branding logo URL. Only available for 'Home' tenant category. - /// A new instance for mocking. - public static TenantData TenantData(string id = null, Guid? tenantId = null, TenantCategory? tenantCategory = null, string country = null, string countryCode = null, string displayName = null, IEnumerable domains = null, string defaultDomain = null, string tenantType = null, Uri tenantBrandingLogoUri = null) - { - domains ??= new List(); - - return new TenantData( - id, - tenantId, - tenantCategory, - country, - countryCode, - displayName, - domains?.ToList(), - defaultDomain, - tenantType, - tenantBrandingLogoUri, - serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// Name of Resource. - /// Type of Resource. - /// Is the resource name Allowed or Reserved. - /// A new instance for mocking. - public static ResourceNameValidationResult ResourceNameValidationResult(string name = null, ResourceType? resourceType = null, ResourceNameValidationStatus? status = null) - { - return new ResourceNameValidationResult(name, resourceType, status, serializedAdditionalRawData: null); - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// Properties of the previewed feature. - /// A new instance for mocking. - public static FeatureData FeatureData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, string featureState = null) - { - return new FeatureData( - id, - name, - resourceType, - systemData, - featureState != null ? new FeatureProperties(featureState, serializedAdditionalRawData: null) : null, - serializedAdditionalRawData: null); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderCollection.cs deleted file mode 100644 index 5915ae4051..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderCollection.cs +++ /dev/null @@ -1,389 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetResourceProviders method from an instance of . - /// - public partial class ResourceProviderCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _resourceProviderProvidersClientDiagnostics; - private readonly ProvidersRestOperations _resourceProviderProvidersRestClient; - - /// Initializes a new instance of the class for mocking. - protected ResourceProviderCollection() - { - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != SubscriptionResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, SubscriptionResource.ResourceType), nameof(id)); - } - - /// - /// Gets the specified resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderCollection.Get"); - scope.Start(); - try - { - var response = await _resourceProviderProvidersRestClient.GetAsync(Id.SubscriptionId, resourceProviderNamespace, expand, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets the specified resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderCollection.Get"); - scope.Start(); - try - { - var response = _resourceProviderProvidersRestClient.Get(Id.SubscriptionId, resourceProviderNamespace, expand, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets all resource providers for a subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers - /// - /// - /// Operation Id - /// Providers_List - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string expand = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _resourceProviderProvidersRestClient.CreateListRequest(Id.SubscriptionId, expand); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _resourceProviderProvidersRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, expand); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new ResourceProviderResource(Client, ResourceProviderData.DeserializeResourceProviderData(e)), _resourceProviderProvidersClientDiagnostics, Pipeline, "ResourceProviderCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Gets all resource providers for a subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers - /// - /// - /// Operation Id - /// Providers_List - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string expand = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _resourceProviderProvidersRestClient.CreateListRequest(Id.SubscriptionId, expand); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _resourceProviderProvidersRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, expand); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new ResourceProviderResource(Client, ResourceProviderData.DeserializeResourceProviderData(e)), _resourceProviderProvidersClientDiagnostics, Pipeline, "ResourceProviderCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderCollection.Exists"); - scope.Start(); - try - { - var response = await _resourceProviderProvidersRestClient.GetAsync(Id.SubscriptionId, resourceProviderNamespace, expand, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderCollection.Exists"); - scope.Start(); - try - { - var response = _resourceProviderProvidersRestClient.Get(Id.SubscriptionId, resourceProviderNamespace, expand, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _resourceProviderProvidersRestClient.GetAsync(Id.SubscriptionId, resourceProviderNamespace, expand, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderCollection.GetIfExists"); - scope.Start(); - try - { - var response = _resourceProviderProvidersRestClient.Get(Id.SubscriptionId, resourceProviderNamespace, expand, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderData.Serialization.cs deleted file mode 100644 index 3b5cd61eb0..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderData.Serialization.cs +++ /dev/null @@ -1,355 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class ResourceProviderData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceProviderData)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (Optional.IsDefined(Namespace)) - { - writer.WritePropertyName("namespace"u8); - writer.WriteStringValue(Namespace); - } - if (options.Format != "W" && Optional.IsDefined(RegistrationState)) - { - writer.WritePropertyName("registrationState"u8); - writer.WriteStringValue(RegistrationState); - } - if (options.Format != "W" && Optional.IsDefined(RegistrationPolicy)) - { - writer.WritePropertyName("registrationPolicy"u8); - writer.WriteStringValue(RegistrationPolicy); - } - if (options.Format != "W" && Optional.IsCollectionDefined(ResourceTypes)) - { - writer.WritePropertyName("resourceTypes"u8); - writer.WriteStartArray(); - foreach (var item in ResourceTypes) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(ProviderAuthorizationConsentState)) - { - writer.WritePropertyName("providerAuthorizationConsentState"u8); - writer.WriteStringValue(ProviderAuthorizationConsentState.Value.ToString()); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResourceProviderData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResourceProviderData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResourceProviderData(document.RootElement, options); - } - - internal static ResourceProviderData DeserializeResourceProviderData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string @namespace = default; - string registrationState = default; - string registrationPolicy = default; - IReadOnlyList resourceTypes = default; - ProviderAuthorizationConsentState? providerAuthorizationConsentState = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("namespace"u8)) - { - @namespace = property.Value.GetString(); - continue; - } - if (property.NameEquals("registrationState"u8)) - { - registrationState = property.Value.GetString(); - continue; - } - if (property.NameEquals("registrationPolicy"u8)) - { - registrationPolicy = property.Value.GetString(); - continue; - } - if (property.NameEquals("resourceTypes"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ProviderResourceType.DeserializeProviderResourceType(item, options)); - } - resourceTypes = array; - continue; - } - if (property.NameEquals("providerAuthorizationConsentState"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - providerAuthorizationConsentState = new ProviderAuthorizationConsentState(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ResourceProviderData( - id, - @namespace, - registrationState, - registrationPolicy, - resourceTypes ?? new ChangeTrackingList(), - providerAuthorizationConsentState, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Namespace), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" namespace: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Namespace)) - { - builder.Append(" namespace: "); - if (Namespace.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Namespace}'''"); - } - else - { - builder.AppendLine($"'{Namespace}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(RegistrationState), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" registrationState: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(RegistrationState)) - { - builder.Append(" registrationState: "); - if (RegistrationState.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{RegistrationState}'''"); - } - else - { - builder.AppendLine($"'{RegistrationState}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(RegistrationPolicy), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" registrationPolicy: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(RegistrationPolicy)) - { - builder.Append(" registrationPolicy: "); - if (RegistrationPolicy.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{RegistrationPolicy}'''"); - } - else - { - builder.AppendLine($"'{RegistrationPolicy}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ResourceTypes), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" resourceTypes: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ResourceTypes)) - { - if (ResourceTypes.Any()) - { - builder.Append(" resourceTypes: "); - builder.AppendLine("["); - foreach (var item in ResourceTypes) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " resourceTypes: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ProviderAuthorizationConsentState), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" providerAuthorizationConsentState: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(ProviderAuthorizationConsentState)) - { - builder.Append(" providerAuthorizationConsentState: "); - builder.AppendLine($"'{ProviderAuthorizationConsentState.Value.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(ResourceProviderData)} does not support writing '{options.Format}' format."); - } - } - - ResourceProviderData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeResourceProviderData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResourceProviderData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderData.cs deleted file mode 100644 index e18d3655a2..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderData.cs +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the ResourceProvider data model. - /// Resource provider information. - /// - public partial class ResourceProviderData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The provider ID. - /// The namespace of the resource provider. - /// The registration state of the resource provider. - /// The registration policy of the resource provider. - /// The collection of provider resource types. - /// The provider authorization consent state. - /// Keeps track of any properties unknown to the library. - internal ResourceProviderData(ResourceIdentifier id, string @namespace, string registrationState, string registrationPolicy, IReadOnlyList resourceTypes, ProviderAuthorizationConsentState? providerAuthorizationConsentState, IDictionary serializedAdditionalRawData) - { - Id = id; - Namespace = @namespace; - RegistrationState = registrationState; - RegistrationPolicy = registrationPolicy; - ResourceTypes = resourceTypes; - ProviderAuthorizationConsentState = providerAuthorizationConsentState; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - /// The namespace of the resource provider. - [WirePath("namespace")] - public string Namespace { get; } - /// The registration state of the resource provider. - [WirePath("registrationState")] - public string RegistrationState { get; } - /// The registration policy of the resource provider. - [WirePath("registrationPolicy")] - public string RegistrationPolicy { get; } - /// The collection of provider resource types. - [WirePath("resourceTypes")] - public IReadOnlyList ResourceTypes { get; } - /// The provider authorization consent state. - [WirePath("providerAuthorizationConsentState")] - public ProviderAuthorizationConsentState? ProviderAuthorizationConsentState { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderResource.Serialization.cs deleted file mode 100644 index cff873e5de..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class ResourceProviderResource : IJsonModel - { - private static ResourceProviderData s_dataDeserializationInstance; - private static ResourceProviderData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - ResourceProviderData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - ResourceProviderData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderResource.cs deleted file mode 100644 index 1644e4e793..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/ResourceProviderResource.cs +++ /dev/null @@ -1,509 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a ResourceProvider along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetResourceProviderResource method. - /// Otherwise you can get one from its parent resource using the GetResourceProvider method. - /// - public partial class ResourceProviderResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The subscriptionId. - /// The resourceProviderNamespace. - public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceProviderNamespace) - { - var resourceId = $"/subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _resourceProviderProvidersClientDiagnostics; - private readonly ProvidersRestOperations _resourceProviderProvidersRestClient; - private readonly ClientDiagnostics _providerResourceTypesClientDiagnostics; - private readonly ProviderResourceTypesRestOperations _providerResourceTypesRestClient; - private readonly ResourceProviderData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Resources/providers"; - - /// Initializes a new instance of the class for mocking. - protected ResourceProviderResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal ResourceProviderResource(ArmClient client, ResourceProviderData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal ResourceProviderResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _resourceProviderProvidersClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string resourceProviderProvidersApiVersion); - _resourceProviderProvidersRestClient = new ProvidersRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, resourceProviderProvidersApiVersion); - _providerResourceTypesClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ProviderConstants.DefaultProviderNamespace, Diagnostics); - _providerResourceTypesRestClient = new ProviderResourceTypesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual ResourceProviderData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// Gets a collection of FeatureResources in the ResourceProvider. - /// An object representing collection of FeatureResources and their operations over a FeatureResource. - public virtual FeatureCollection GetFeatures() - { - return GetCachedClient(client => new FeatureCollection(client, Id)); - } - - /// - /// Gets the preview feature with the specified name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the feature to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetFeatureAsync(string featureName, CancellationToken cancellationToken = default) - { - return await GetFeatures().GetAsync(featureName, cancellationToken).ConfigureAwait(false); - } - - /// - /// Gets the preview feature with the specified name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - /// - /// - /// Operation Id - /// Features_Get - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the feature to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetFeature(string featureName, CancellationToken cancellationToken = default) - { - return GetFeatures().Get(featureName, cancellationToken); - } - - /// - /// Gets the specified resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - public virtual async Task> GetAsync(string expand = null, CancellationToken cancellationToken = default) - { - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderResource.Get"); - scope.Start(); - try - { - var response = await _resourceProviderProvidersRestClient.GetAsync(Id.SubscriptionId, Id.Provider, expand, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets the specified resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - public virtual Response Get(string expand = null, CancellationToken cancellationToken = default) - { - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderResource.Get"); - scope.Start(); - try - { - var response = _resourceProviderProvidersRestClient.Get(Id.SubscriptionId, Id.Provider, expand, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Unregisters a subscription from a resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/unregister - /// - /// - /// Operation Id - /// Providers_Unregister - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> UnregisterAsync(CancellationToken cancellationToken = default) - { - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderResource.Unregister"); - scope.Start(); - try - { - var response = await _resourceProviderProvidersRestClient.UnregisterAsync(Id.SubscriptionId, Id.Provider, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Unregisters a subscription from a resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/unregister - /// - /// - /// Operation Id - /// Providers_Unregister - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Unregister(CancellationToken cancellationToken = default) - { - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderResource.Unregister"); - scope.Start(); - try - { - var response = _resourceProviderProvidersRestClient.Unregister(Id.SubscriptionId, Id.Provider, cancellationToken); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Get the provider permissions. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/providerPermissions - /// - /// - /// Operation Id - /// Providers_ProviderPermissions - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable ProviderPermissionsAsync(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _resourceProviderProvidersRestClient.CreateProviderPermissionsRequest(Id.SubscriptionId, Id.Provider); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, null, e => ProviderPermission.DeserializeProviderPermission(e), _resourceProviderProvidersClientDiagnostics, Pipeline, "ResourceProviderResource.ProviderPermissions", "value", null, cancellationToken); - } - - /// - /// Get the provider permissions. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/providerPermissions - /// - /// - /// Operation Id - /// Providers_ProviderPermissions - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable ProviderPermissions(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _resourceProviderProvidersRestClient.CreateProviderPermissionsRequest(Id.SubscriptionId, Id.Provider); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, null, e => ProviderPermission.DeserializeProviderPermission(e), _resourceProviderProvidersClientDiagnostics, Pipeline, "ResourceProviderResource.ProviderPermissions", "value", null, cancellationToken); - } - - /// - /// Registers a subscription with a resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/register - /// - /// - /// Operation Id - /// Providers_Register - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The third party consent for S2S. - /// The cancellation token to use. - public virtual async Task> RegisterAsync(ProviderRegistrationContent content = null, CancellationToken cancellationToken = default) - { - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderResource.Register"); - scope.Start(); - try - { - var response = await _resourceProviderProvidersRestClient.RegisterAsync(Id.SubscriptionId, Id.Provider, content, cancellationToken).ConfigureAwait(false); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Registers a subscription with a resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/register - /// - /// - /// Operation Id - /// Providers_Register - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The third party consent for S2S. - /// The cancellation token to use. - public virtual Response Register(ProviderRegistrationContent content = null, CancellationToken cancellationToken = default) - { - using var scope = _resourceProviderProvidersClientDiagnostics.CreateScope("ResourceProviderResource.Register"); - scope.Start(); - try - { - var response = _resourceProviderProvidersRestClient.Register(Id.SubscriptionId, Id.Provider, content, cancellationToken); - return Response.FromValue(new ResourceProviderResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// List the resource types for a specified resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/resourceTypes - /// - /// - /// Operation Id - /// ProviderResourceTypes_List - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetProviderResourceTypesAsync(string expand = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _providerResourceTypesRestClient.CreateListRequest(Id.SubscriptionId, Id.Provider, expand); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, null, e => ProviderResourceType.DeserializeProviderResourceType(e), _providerResourceTypesClientDiagnostics, Pipeline, "ResourceProviderResource.GetProviderResourceTypes", "value", null, cancellationToken); - } - - /// - /// List the resource types for a specified resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/resourceTypes - /// - /// - /// Operation Id - /// ProviderResourceTypes_List - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetProviderResourceTypes(string expand = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _providerResourceTypesRestClient.CreateListRequest(Id.SubscriptionId, Id.Provider, expand); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, null, e => ProviderResourceType.DeserializeProviderResourceType(e), _providerResourceTypesClientDiagnostics, Pipeline, "ResourceProviderResource.GetProviderResourceTypes", "value", null, cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/DataPolicyManifestsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/DataPolicyManifestsRestOperations.cs deleted file mode 100644 index b94f641cd7..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/DataPolicyManifestsRestOperations.cs +++ /dev/null @@ -1,265 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class DataPolicyManifestsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of DataPolicyManifestsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public DataPolicyManifestsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2020-09-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateGetByPolicyModeRequestUri(string policyMode) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/dataPolicyManifests/", false); - uri.AppendPath(policyMode, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetByPolicyModeRequest(string policyMode) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/dataPolicyManifests/", false); - uri.AppendPath(policyMode, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the data policy manifest with the given policy mode. - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetByPolicyModeAsync(string policyMode, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyMode, nameof(policyMode)); - - using var message = CreateGetByPolicyModeRequest(policyMode); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - DataPolicyManifestData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = DataPolicyManifestData.DeserializeDataPolicyManifestData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((DataPolicyManifestData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the data policy manifest with the given policy mode. - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response GetByPolicyMode(string policyMode, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyMode, nameof(policyMode)); - - using var message = CreateGetByPolicyModeRequest(policyMode); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - DataPolicyManifestData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = DataPolicyManifestData.DeserializeDataPolicyManifestData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((DataPolicyManifestData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri(string filter) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/dataPolicyManifests", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - return uri; - } - - internal HttpMessage CreateListRequest(string filter) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/dataPolicyManifests", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the data policy manifests that match the optional given $filter. Valid values for $filter are: "$filter=namespace eq '{0}'". If $filter is not provided, the unfiltered list includes all data policy manifests for data resource types. If $filter=namespace is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The filter to apply on the operation. Valid values for $filter are: "namespace eq '{value}'". If $filter is not provided, no filtering is performed. If $filter=namespace eq '{value}' is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The cancellation token to use. - public async Task> ListAsync(string filter = null, CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(filter); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - DataPolicyManifestListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = DataPolicyManifestListResult.DeserializeDataPolicyManifestListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the data policy manifests that match the optional given $filter. Valid values for $filter are: "$filter=namespace eq '{0}'". If $filter is not provided, the unfiltered list includes all data policy manifests for data resource types. If $filter=namespace is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The filter to apply on the operation. Valid values for $filter are: "namespace eq '{value}'". If $filter is not provided, no filtering is performed. If $filter=namespace eq '{value}' is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The cancellation token to use. - public Response List(string filter = null, CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(filter); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - DataPolicyManifestListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = DataPolicyManifestListResult.DeserializeDataPolicyManifestListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string filter) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string filter) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the data policy manifests that match the optional given $filter. Valid values for $filter are: "$filter=namespace eq '{0}'". If $filter is not provided, the unfiltered list includes all data policy manifests for data resource types. If $filter=namespace is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The URL to the next page of results. - /// The filter to apply on the operation. Valid values for $filter are: "namespace eq '{value}'". If $filter is not provided, no filtering is performed. If $filter=namespace eq '{value}' is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The cancellation token to use. - /// is null. - public async Task> ListNextPageAsync(string nextLink, string filter = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink, filter); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - DataPolicyManifestListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = DataPolicyManifestListResult.DeserializeDataPolicyManifestListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the data policy manifests that match the optional given $filter. Valid values for $filter are: "$filter=namespace eq '{0}'". If $filter is not provided, the unfiltered list includes all data policy manifests for data resource types. If $filter=namespace is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The URL to the next page of results. - /// The filter to apply on the operation. Valid values for $filter are: "namespace eq '{value}'". If $filter is not provided, no filtering is performed. If $filter=namespace eq '{value}' is provided, the returned list only includes all data policy manifests that have a namespace matching the provided value. - /// The cancellation token to use. - /// is null. - public Response ListNextPage(string nextLink, string filter = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink, filter); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - DataPolicyManifestListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = DataPolicyManifestListResult.DeserializeDataPolicyManifestListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/FeaturesRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/FeaturesRestOperations.cs deleted file mode 100644 index 6eda9037c4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/FeaturesRestOperations.cs +++ /dev/null @@ -1,643 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class FeaturesRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of FeaturesRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public FeaturesRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2021-07-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateListAllRequestUri(string subscriptionId) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/features", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListAllRequest(string subscriptionId) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/features", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json, text/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all the preview features that are available through AFEC for the subscription. - /// The ID of the target subscription. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListAllAsync(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListAllRequest(subscriptionId); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - FeatureOperationsListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = FeatureOperationsListResult.DeserializeFeatureOperationsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all the preview features that are available through AFEC for the subscription. - /// The ID of the target subscription. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response ListAll(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListAllRequest(subscriptionId); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - FeatureOperationsListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = FeatureOperationsListResult.DeserializeFeatureOperationsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri(string subscriptionId, string resourceProviderNamespace) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/features", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListRequest(string subscriptionId, string resourceProviderNamespace) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/features", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json, text/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all the preview features in a provider namespace that are available through AFEC for the subscription. - /// The ID of the target subscription. - /// The namespace of the resource provider for getting features. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> ListAsync(string subscriptionId, string resourceProviderNamespace, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateListRequest(subscriptionId, resourceProviderNamespace); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - FeatureOperationsListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = FeatureOperationsListResult.DeserializeFeatureOperationsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all the preview features in a provider namespace that are available through AFEC for the subscription. - /// The ID of the target subscription. - /// The namespace of the resource provider for getting features. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response List(string subscriptionId, string resourceProviderNamespace, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateListRequest(subscriptionId, resourceProviderNamespace); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - FeatureOperationsListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = FeatureOperationsListResult.DeserializeFeatureOperationsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetRequestUri(string subscriptionId, string resourceProviderNamespace, string featureName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/features/", false); - uri.AppendPath(featureName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetRequest(string subscriptionId, string resourceProviderNamespace, string featureName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/features/", false); - uri.AppendPath(featureName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json, text/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets the preview feature with the specified name. - /// The ID of the target subscription. - /// The resource provider namespace for the feature. - /// The name of the feature to get. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public async Task> GetAsync(string subscriptionId, string resourceProviderNamespace, string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var message = CreateGetRequest(subscriptionId, resourceProviderNamespace, featureName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - FeatureData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = FeatureData.DeserializeFeatureData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((FeatureData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets the preview feature with the specified name. - /// The ID of the target subscription. - /// The resource provider namespace for the feature. - /// The name of the feature to get. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public Response Get(string subscriptionId, string resourceProviderNamespace, string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var message = CreateGetRequest(subscriptionId, resourceProviderNamespace, featureName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - FeatureData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = FeatureData.DeserializeFeatureData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((FeatureData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateRegisterRequestUri(string subscriptionId, string resourceProviderNamespace, string featureName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/features/", false); - uri.AppendPath(featureName, true); - uri.AppendPath("/register", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateRegisterRequest(string subscriptionId, string resourceProviderNamespace, string featureName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/features/", false); - uri.AppendPath(featureName, true); - uri.AppendPath("/register", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json, text/json"); - _userAgent.Apply(message); - return message; - } - - /// Registers the preview feature for the subscription. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The name of the feature to register. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public async Task> RegisterAsync(string subscriptionId, string resourceProviderNamespace, string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var message = CreateRegisterRequest(subscriptionId, resourceProviderNamespace, featureName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - FeatureData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = FeatureData.DeserializeFeatureData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Registers the preview feature for the subscription. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The name of the feature to register. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public Response Register(string subscriptionId, string resourceProviderNamespace, string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var message = CreateRegisterRequest(subscriptionId, resourceProviderNamespace, featureName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - FeatureData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = FeatureData.DeserializeFeatureData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateUnregisterRequestUri(string subscriptionId, string resourceProviderNamespace, string featureName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/features/", false); - uri.AppendPath(featureName, true); - uri.AppendPath("/unregister", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateUnregisterRequest(string subscriptionId, string resourceProviderNamespace, string featureName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Features/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/features/", false); - uri.AppendPath(featureName, true); - uri.AppendPath("/unregister", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json, text/json"); - _userAgent.Apply(message); - return message; - } - - /// Unregisters the preview feature for the subscription. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The name of the feature to unregister. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public async Task> UnregisterAsync(string subscriptionId, string resourceProviderNamespace, string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var message = CreateUnregisterRequest(subscriptionId, resourceProviderNamespace, featureName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - FeatureData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = FeatureData.DeserializeFeatureData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Unregisters the preview feature for the subscription. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The name of the feature to unregister. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public Response Unregister(string subscriptionId, string resourceProviderNamespace, string featureName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNullOrEmpty(featureName, nameof(featureName)); - - using var message = CreateUnregisterRequest(subscriptionId, resourceProviderNamespace, featureName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - FeatureData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = FeatureData.DeserializeFeatureData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListAllNextPageRequestUri(string nextLink, string subscriptionId) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListAllNextPageRequest(string nextLink, string subscriptionId) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json, text/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all the preview features that are available through AFEC for the subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListAllNextPageAsync(string nextLink, string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListAllNextPageRequest(nextLink, subscriptionId); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - FeatureOperationsListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = FeatureOperationsListResult.DeserializeFeatureOperationsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all the preview features that are available through AFEC for the subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListAllNextPage(string nextLink, string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListAllNextPageRequest(nextLink, subscriptionId); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - FeatureOperationsListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = FeatureOperationsListResult.DeserializeFeatureOperationsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string subscriptionId, string resourceProviderNamespace) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string resourceProviderNamespace) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json, text/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all the preview features in a provider namespace that are available through AFEC for the subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The namespace of the resource provider for getting features. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> ListNextPageAsync(string nextLink, string subscriptionId, string resourceProviderNamespace, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceProviderNamespace); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - FeatureOperationsListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = FeatureOperationsListResult.DeserializeFeatureOperationsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all the preview features in a provider namespace that are available through AFEC for the subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The namespace of the resource provider for getting features. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response ListNextPage(string nextLink, string subscriptionId, string resourceProviderNamespace, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceProviderNamespace); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - FeatureOperationsListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = FeatureOperationsListResult.DeserializeFeatureOperationsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ManagementLocksRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ManagementLocksRestOperations.cs deleted file mode 100644 index 66b3dc6664..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ManagementLocksRestOperations.cs +++ /dev/null @@ -1,459 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class ManagementLocksRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of ManagementLocksRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public ManagementLocksRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2020-05-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateCreateOrUpdateByScopeRequestUri(string scope, string lockName, ManagementLockData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/locks/", false); - uri.AppendPath(lockName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateByScopeRequest(string scope, string lockName, ManagementLockData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/locks/", false); - uri.AppendPath(lockName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// Create or update a management lock by scope. - /// The scope for the lock. When providing a scope for the assignment, use '/subscriptions/{subscriptionId}' for subscriptions, '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' for resources. - /// The name of lock. - /// Create or update management lock parameters. - /// The cancellation token to use. - /// , or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> CreateOrUpdateByScopeAsync(string scope, string lockName, ManagementLockData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateByScopeRequest(scope, lockName, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 201: - { - ManagementLockData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementLockData.DeserializeManagementLockData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Create or update a management lock by scope. - /// The scope for the lock. When providing a scope for the assignment, use '/subscriptions/{subscriptionId}' for subscriptions, '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' for resources. - /// The name of lock. - /// Create or update management lock parameters. - /// The cancellation token to use. - /// , or is null. - /// is an empty string, and was expected to be non-empty. - public Response CreateOrUpdateByScope(string scope, string lockName, ManagementLockData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateByScopeRequest(scope, lockName, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 201: - { - ManagementLockData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementLockData.DeserializeManagementLockData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteByScopeRequestUri(string scope, string lockName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/locks/", false); - uri.AppendPath(lockName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteByScopeRequest(string scope, string lockName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/locks/", false); - uri.AppendPath(lockName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Delete a management lock by scope. - /// The scope for the lock. - /// The name of lock. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task DeleteByScopeAsync(string scope, string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var message = CreateDeleteByScopeRequest(scope, lockName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// Delete a management lock by scope. - /// The scope for the lock. - /// The name of lock. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response DeleteByScope(string scope, string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var message = CreateDeleteByScopeRequest(scope, lockName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetByScopeRequestUri(string scope, string lockName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/locks/", false); - uri.AppendPath(lockName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetByScopeRequest(string scope, string lockName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/locks/", false); - uri.AppendPath(lockName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Get a management lock by scope. - /// The scope for the lock. - /// The name of lock. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetByScopeAsync(string scope, string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var message = CreateGetByScopeRequest(scope, lockName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementLockData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementLockData.DeserializeManagementLockData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ManagementLockData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// Get a management lock by scope. - /// The scope for the lock. - /// The name of lock. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response GetByScope(string scope, string lockName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(lockName, nameof(lockName)); - - using var message = CreateGetByScopeRequest(scope, lockName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementLockData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementLockData.DeserializeManagementLockData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ManagementLockData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListByScopeRequestUri(string scope, string filter) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/locks", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListByScopeRequest(string scope, string filter) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/locks", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all the management locks for a scope. - /// The scope for the lock. When providing a scope for the assignment, use '/subscriptions/{subscriptionId}' for subscriptions, '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' for resources. - /// The filter to apply on the operation. - /// The cancellation token to use. - /// is null. - public async Task> ListByScopeAsync(string scope, string filter = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - - using var message = CreateListByScopeRequest(scope, filter); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementLockListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementLockListResult.DeserializeManagementLockListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all the management locks for a scope. - /// The scope for the lock. When providing a scope for the assignment, use '/subscriptions/{subscriptionId}' for subscriptions, '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' for resources. - /// The filter to apply on the operation. - /// The cancellation token to use. - /// is null. - public Response ListByScope(string scope, string filter = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - - using var message = CreateListByScopeRequest(scope, filter); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementLockListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementLockListResult.DeserializeManagementLockListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListByScopeNextPageRequestUri(string nextLink, string scope, string filter) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListByScopeNextPageRequest(string nextLink, string scope, string filter) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all the management locks for a scope. - /// The URL to the next page of results. - /// The scope for the lock. When providing a scope for the assignment, use '/subscriptions/{subscriptionId}' for subscriptions, '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' for resources. - /// The filter to apply on the operation. - /// The cancellation token to use. - /// or is null. - public async Task> ListByScopeNextPageAsync(string nextLink, string scope, string filter = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNull(scope, nameof(scope)); - - using var message = CreateListByScopeNextPageRequest(nextLink, scope, filter); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ManagementLockListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ManagementLockListResult.DeserializeManagementLockListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all the management locks for a scope. - /// The URL to the next page of results. - /// The scope for the lock. When providing a scope for the assignment, use '/subscriptions/{subscriptionId}' for subscriptions, '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for resource groups, and '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}' for resources. - /// The filter to apply on the operation. - /// The cancellation token to use. - /// or is null. - public Response ListByScopeNextPage(string nextLink, string scope, string filter = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNull(scope, nameof(scope)); - - using var message = CreateListByScopeNextPageRequest(nextLink, scope, filter); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ManagementLockListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ManagementLockListResult.DeserializeManagementLockListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicyAssignmentsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicyAssignmentsRestOperations.cs deleted file mode 100644 index 8437bfbc9f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicyAssignmentsRestOperations.cs +++ /dev/null @@ -1,1183 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class PolicyAssignmentsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of PolicyAssignmentsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public PolicyAssignmentsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2022-06-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateDeleteRequestUri(string scope, string policyAssignmentName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments/", false); - uri.AppendPath(policyAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteRequest(string scope, string policyAssignmentName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments/", false); - uri.AppendPath(policyAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation deletes a policy assignment, given its name and the scope it was created in. The scope of a policy assignment is the part of its ID preceding '/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. - /// The scope of the policy assignment. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - /// The name of the policy assignment to delete. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> DeleteAsync(string scope, string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var message = CreateDeleteRequest(scope, policyAssignmentName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentData.DeserializePolicyAssignmentData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 204: - return Response.FromValue((PolicyAssignmentData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation deletes a policy assignment, given its name and the scope it was created in. The scope of a policy assignment is the part of its ID preceding '/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. - /// The scope of the policy assignment. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - /// The name of the policy assignment to delete. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response Delete(string scope, string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var message = CreateDeleteRequest(scope, policyAssignmentName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentData.DeserializePolicyAssignmentData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 204: - return Response.FromValue((PolicyAssignmentData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateCreateRequestUri(string scope, string policyAssignmentName, PolicyAssignmentData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments/", false); - uri.AppendPath(policyAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateRequest(string scope, string policyAssignmentName, PolicyAssignmentData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments/", false); - uri.AppendPath(policyAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// The scope of the policy assignment. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - /// The name of the policy assignment. - /// Parameters for the policy assignment. - /// The cancellation token to use. - /// , or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> CreateAsync(string scope, string policyAssignmentName, PolicyAssignmentData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateRequest(scope, policyAssignmentName, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 201: - { - PolicyAssignmentData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentData.DeserializePolicyAssignmentData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation creates or updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// The scope of the policy assignment. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - /// The name of the policy assignment. - /// Parameters for the policy assignment. - /// The cancellation token to use. - /// , or is null. - /// is an empty string, and was expected to be non-empty. - public Response Create(string scope, string policyAssignmentName, PolicyAssignmentData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateRequest(scope, policyAssignmentName, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 201: - { - PolicyAssignmentData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentData.DeserializePolicyAssignmentData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetRequestUri(string scope, string policyAssignmentName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments/", false); - uri.AppendPath(policyAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetRequest(string scope, string policyAssignmentName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments/", false); - uri.AppendPath(policyAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a single policy assignment, given its name and the scope it was created at. - /// The scope of the policy assignment. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetAsync(string scope, string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var message = CreateGetRequest(scope, policyAssignmentName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentData.DeserializePolicyAssignmentData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicyAssignmentData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a single policy assignment, given its name and the scope it was created at. - /// The scope of the policy assignment. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - /// The name of the policy assignment to get. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response Get(string scope, string policyAssignmentName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - - using var message = CreateGetRequest(scope, policyAssignmentName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentData.DeserializePolicyAssignmentData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicyAssignmentData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateUpdateRequestUri(string scope, string policyAssignmentName, PolicyAssignmentPatch patch) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments/", false); - uri.AppendPath(policyAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateUpdateRequest(string scope, string policyAssignmentName, PolicyAssignmentPatch patch) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Patch; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments/", false); - uri.AppendPath(policyAssignmentName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(patch, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// This operation updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// The scope of the policy assignment. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - /// The name of the policy assignment. - /// Parameters for policy assignment patch request. - /// The cancellation token to use. - /// , or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> UpdateAsync(string scope, string policyAssignmentName, PolicyAssignmentPatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - Argument.AssertNotNull(patch, nameof(patch)); - - using var message = CreateUpdateRequest(scope, policyAssignmentName, patch); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentData.DeserializePolicyAssignmentData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation updates a policy assignment with the given scope and name. Policy assignments apply to all resources contained within their scope. For example, when you assign a policy at resource group scope, that policy applies to all resources in the group. - /// The scope of the policy assignment. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. - /// The name of the policy assignment. - /// Parameters for policy assignment patch request. - /// The cancellation token to use. - /// , or is null. - /// is an empty string, and was expected to be non-empty. - public Response Update(string scope, string policyAssignmentName, PolicyAssignmentPatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNullOrEmpty(policyAssignmentName, nameof(policyAssignmentName)); - Argument.AssertNotNull(patch, nameof(patch)); - - using var message = CreateUpdateRequest(scope, policyAssignmentName, patch); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentData.DeserializePolicyAssignmentData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListForResourceGroupRequestUri(string subscriptionId, string resourceGroupName, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListForResourceGroupRequest(string subscriptionId, string resourceGroupName, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the list of all policy assignments associated with the given resource group in the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource group, including those that apply directly or apply from containing scopes, as well as any applied to resources contained within the resource group. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource group, which is everything in the unfiltered list except those applied to resources contained within the resource group. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource group. - /// The ID of the target subscription. - /// The name of the resource group that contains policy assignments. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> ListForResourceGroupAsync(string subscriptionId, string resourceGroupName, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateListForResourceGroupRequest(subscriptionId, resourceGroupName, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the list of all policy assignments associated with the given resource group in the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource group, including those that apply directly or apply from containing scopes, as well as any applied to resources contained within the resource group. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource group, which is everything in the unfiltered list except those applied to resources contained within the resource group. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource group. - /// The ID of the target subscription. - /// The name of the resource group that contains policy assignments. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response ListForResourceGroup(string subscriptionId, string resourceGroupName, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateListForResourceGroupRequest(subscriptionId, resourceGroupName, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListForResourceRequestUri(string subscriptionId, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/", false); - uri.AppendPath(parentResourcePath, false); - uri.AppendPath("/", false); - uri.AppendPath(resourceType, false); - uri.AppendPath("/", false); - uri.AppendPath(resourceName, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListForResourceRequest(string subscriptionId, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/", false); - uri.AppendPath(parentResourcePath, false); - uri.AppendPath("/", false); - uri.AppendPath(resourceType, false); - uri.AppendPath("/", false); - uri.AppendPath(resourceName, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the list of all policy assignments associated with the specified resource in the given resource group and subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource, including those that apply directly or from all containing scopes, as well as any applied to resources contained within the resource. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource, which is everything in the unfiltered list except those applied to resources contained within the resource. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource level. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource. Three parameters plus the resource name are used to identify a specific resource. If the resource is not part of a parent resource (the more common case), the parent resource path should not be provided (or provided as ''). For example a web app could be specified as ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', {resourceType} == 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent resource, then all parameters should be provided. For example a virtual machine DNS name could be specified as ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == 'MyComputerName'). A convenient alternative to providing the namespace and type name separately is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == 'MyWebApp'). - /// The ID of the target subscription. - /// The name of the resource group containing the resource. - /// The namespace of the resource provider. For example, the namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). - /// The parent resource path. Use empty string if there is none. - /// The resource type name. For example the type name of a web app is 'sites' (from Microsoft.Web/sites). - /// The name of the resource. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// , , , , or is null. - /// , , or is an empty string, and was expected to be non-empty. - public async Task> ListForResourceAsync(string subscriptionId, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNull(parentResourcePath, nameof(parentResourcePath)); - Argument.AssertNotNull(resourceType, nameof(resourceType)); - Argument.AssertNotNullOrEmpty(resourceName, nameof(resourceName)); - - using var message = CreateListForResourceRequest(subscriptionId, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the list of all policy assignments associated with the specified resource in the given resource group and subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource, including those that apply directly or from all containing scopes, as well as any applied to resources contained within the resource. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource, which is everything in the unfiltered list except those applied to resources contained within the resource. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource level. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource. Three parameters plus the resource name are used to identify a specific resource. If the resource is not part of a parent resource (the more common case), the parent resource path should not be provided (or provided as ''). For example a web app could be specified as ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', {resourceType} == 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent resource, then all parameters should be provided. For example a virtual machine DNS name could be specified as ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == 'MyComputerName'). A convenient alternative to providing the namespace and type name separately is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == 'MyWebApp'). - /// The ID of the target subscription. - /// The name of the resource group containing the resource. - /// The namespace of the resource provider. For example, the namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). - /// The parent resource path. Use empty string if there is none. - /// The resource type name. For example the type name of a web app is 'sites' (from Microsoft.Web/sites). - /// The name of the resource. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// , , , , or is null. - /// , , or is an empty string, and was expected to be non-empty. - public Response ListForResource(string subscriptionId, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNull(parentResourcePath, nameof(parentResourcePath)); - Argument.AssertNotNull(resourceType, nameof(resourceType)); - Argument.AssertNotNullOrEmpty(resourceName, nameof(resourceName)); - - using var message = CreateListForResourceRequest(subscriptionId, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListForManagementGroupRequestUri(string managementGroupId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListForManagementGroupRequest(string managementGroupId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the list of all policy assignments applicable to the management group that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter=atScope() is provided, the returned list includes all policy assignments that are assigned to the management group or the management group's ancestors. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the management group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the management group. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListForManagementGroupAsync(string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListForManagementGroupRequest(managementGroupId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the list of all policy assignments applicable to the management group that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter=atScope() is provided, the returned list includes all policy assignments that are assigned to the management group or the management group's ancestors. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the management group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the management group. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response ListForManagementGroup(string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListForManagementGroupRequest(managementGroupId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri(string subscriptionId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListRequest(string subscriptionId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyAssignments", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the list of all policy assignments associated with the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the subscription, including those that apply directly or from management groups that contain the given subscription, as well as any applied to objects contained within the subscription. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the subscription, which is everything in the unfiltered list except those applied to objects contained within the subscription. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the subscription. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListAsync(string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the list of all policy assignments associated with the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the subscription, including those that apply directly or from management groups that contain the given subscription, as well as any applied to objects contained within the subscription. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the subscription, which is everything in the unfiltered list except those applied to objects contained within the subscription. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the subscription. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response List(string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListForResourceGroupNextPageRequestUri(string nextLink, string subscriptionId, string resourceGroupName, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListForResourceGroupNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the list of all policy assignments associated with the given resource group in the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource group, including those that apply directly or apply from containing scopes, as well as any applied to resources contained within the resource group. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource group, which is everything in the unfiltered list except those applied to resources contained within the resource group. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource group. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The name of the resource group that contains policy assignments. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> ListForResourceGroupNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateListForResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the list of all policy assignments associated with the given resource group in the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource group, including those that apply directly or apply from containing scopes, as well as any applied to resources contained within the resource group. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource group, which is everything in the unfiltered list except those applied to resources contained within the resource group. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource group. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The name of the resource group that contains policy assignments. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response ListForResourceGroupNextPage(string nextLink, string subscriptionId, string resourceGroupName, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateListForResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListForResourceNextPageRequestUri(string nextLink, string subscriptionId, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListForResourceNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the list of all policy assignments associated with the specified resource in the given resource group and subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource, including those that apply directly or from all containing scopes, as well as any applied to resources contained within the resource. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource, which is everything in the unfiltered list except those applied to resources contained within the resource. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource level. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource. Three parameters plus the resource name are used to identify a specific resource. If the resource is not part of a parent resource (the more common case), the parent resource path should not be provided (or provided as ''). For example a web app could be specified as ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', {resourceType} == 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent resource, then all parameters should be provided. For example a virtual machine DNS name could be specified as ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == 'MyComputerName'). A convenient alternative to providing the namespace and type name separately is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == 'MyWebApp'). - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The name of the resource group containing the resource. - /// The namespace of the resource provider. For example, the namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). - /// The parent resource path. Use empty string if there is none. - /// The resource type name. For example the type name of a web app is 'sites' (from Microsoft.Web/sites). - /// The name of the resource. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// , , , , , or is null. - /// , , or is an empty string, and was expected to be non-empty. - public async Task> ListForResourceNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNull(parentResourcePath, nameof(parentResourcePath)); - Argument.AssertNotNull(resourceType, nameof(resourceType)); - Argument.AssertNotNullOrEmpty(resourceName, nameof(resourceName)); - - using var message = CreateListForResourceNextPageRequest(nextLink, subscriptionId, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the list of all policy assignments associated with the specified resource in the given resource group and subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the resource, including those that apply directly or from all containing scopes, as well as any applied to resources contained within the resource. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the resource, which is everything in the unfiltered list except those applied to resources contained within the resource. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the resource level. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the resource. Three parameters plus the resource name are used to identify a specific resource. If the resource is not part of a parent resource (the more common case), the parent resource path should not be provided (or provided as ''). For example a web app could be specified as ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == '', {resourceType} == 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent resource, then all parameters should be provided. For example a virtual machine DNS name could be specified as ({resourceProviderNamespace} == 'Microsoft.Compute', {parentResourcePath} == 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames', {resourceName} == 'MyComputerName'). A convenient alternative to providing the namespace and type name separately is to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == '', {parentResourcePath} == '', {resourceType} == 'Microsoft.Web/sites', {resourceName} == 'MyWebApp'). - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The name of the resource group containing the resource. - /// The namespace of the resource provider. For example, the namespace of a virtual machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines). - /// The parent resource path. Use empty string if there is none. - /// The resource type name. For example the type name of a web app is 'sites' (from Microsoft.Web/sites). - /// The name of the resource. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// , , , , , or is null. - /// , , or is an empty string, and was expected to be non-empty. - public Response ListForResourceNextPage(string nextLink, string subscriptionId, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - Argument.AssertNotNull(parentResourcePath, nameof(parentResourcePath)); - Argument.AssertNotNull(resourceType, nameof(resourceType)); - Argument.AssertNotNullOrEmpty(resourceName, nameof(resourceName)); - - using var message = CreateListForResourceNextPageRequest(nextLink, subscriptionId, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListForManagementGroupNextPageRequestUri(string nextLink, string managementGroupId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListForManagementGroupNextPageRequest(string nextLink, string managementGroupId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the list of all policy assignments applicable to the management group that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter=atScope() is provided, the returned list includes all policy assignments that are assigned to the management group or the management group's ancestors. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the management group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the management group. - /// The URL to the next page of results. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListForManagementGroupNextPageAsync(string nextLink, string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListForManagementGroupNextPageRequest(nextLink, managementGroupId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the list of all policy assignments applicable to the management group that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter=atScope() is provided, the returned list includes all policy assignments that are assigned to the management group or the management group's ancestors. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the management group. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value} that apply to the management group. - /// The URL to the next page of results. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListForManagementGroupNextPage(string nextLink, string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListForManagementGroupNextPageRequest(nextLink, managementGroupId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string subscriptionId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the list of all policy assignments associated with the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the subscription, including those that apply directly or from management groups that contain the given subscription, as well as any applied to objects contained within the subscription. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the subscription, which is everything in the unfiltered list except those applied to objects contained within the subscription. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the subscription. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListNextPageAsync(string nextLink, string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the list of all policy assignments associated with the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, the unfiltered list includes all policy assignments associated with the subscription, including those that apply directly or from management groups that contain the given subscription, as well as any applied to objects contained within the subscription. If $filter=atScope() is provided, the returned list includes all policy assignments that apply to the subscription, which is everything in the unfiltered list except those applied to objects contained within the subscription. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the subscription. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()' or 'policyDefinitionId eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atScope() is provided, the returned list only includes all policy assignments that apply to the scope, which is everything in the unfiltered list except those applied to sub scopes contained within the given scope. If $filter=atExactScope() is provided, the returned list only includes all policy assignments that at the given scope. If $filter=policyDefinitionId eq '{value}' is provided, the returned list includes all policy assignments of the policy definition whose id is {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListNextPage(string nextLink, string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyAssignmentListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyAssignmentListResult.DeserializePolicyAssignmentListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicyDefinitionsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicyDefinitionsRestOperations.cs deleted file mode 100644 index d8a8f6ee24..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicyDefinitionsRestOperations.cs +++ /dev/null @@ -1,1145 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class PolicyDefinitionsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of PolicyDefinitionsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public PolicyDefinitionsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2021-06-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateCreateOrUpdateRequestUri(string subscriptionId, string policyDefinitionName, PolicyDefinitionData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string policyDefinitionName, PolicyDefinitionData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// This operation creates or updates a policy definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy definition to create. - /// The policy definition properties. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> CreateOrUpdateAsync(string subscriptionId, string policyDefinitionName, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateRequest(subscriptionId, policyDefinitionName, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 201: - { - PolicyDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation creates or updates a policy definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy definition to create. - /// The policy definition properties. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response CreateOrUpdate(string subscriptionId, string policyDefinitionName, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateRequest(subscriptionId, policyDefinitionName, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 201: - { - PolicyDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteRequestUri(string subscriptionId, string policyDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteRequest(string subscriptionId, string policyDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation deletes the policy definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy definition to delete. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task DeleteAsync(string subscriptionId, string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateDeleteRequest(subscriptionId, policyDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation deletes the policy definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy definition to delete. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Delete(string subscriptionId, string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateDeleteRequest(subscriptionId, policyDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetRequestUri(string subscriptionId, string policyDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetRequest(string subscriptionId, string policyDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the policy definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy definition to get. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> GetAsync(string subscriptionId, string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateGetRequest(subscriptionId, policyDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicyDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the policy definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy definition to get. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Get(string subscriptionId, string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateGetRequest(subscriptionId, policyDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicyDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetBuiltInRequestUri(string policyDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetBuiltInRequest(string policyDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the built-in policy definition with the given name. - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetBuiltInAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateGetBuiltInRequest(policyDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicyDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the built-in policy definition with the given name. - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response GetBuiltIn(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateGetBuiltInRequest(policyDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicyDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateCreateOrUpdateAtManagementGroupRequestUri(string managementGroupId, string policyDefinitionName, PolicyDefinitionData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateAtManagementGroupRequest(string managementGroupId, string policyDefinitionName, PolicyDefinitionData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// This operation creates or updates a policy definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy definition to create. - /// The policy definition properties. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> CreateOrUpdateAtManagementGroupAsync(string managementGroupId, string policyDefinitionName, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateAtManagementGroupRequest(managementGroupId, policyDefinitionName, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 201: - { - PolicyDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation creates or updates a policy definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy definition to create. - /// The policy definition properties. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response CreateOrUpdateAtManagementGroup(string managementGroupId, string policyDefinitionName, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateAtManagementGroupRequest(managementGroupId, policyDefinitionName, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 201: - { - PolicyDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteAtManagementGroupRequestUri(string managementGroupId, string policyDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteAtManagementGroupRequest(string managementGroupId, string policyDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation deletes the policy definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy definition to delete. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task DeleteAtManagementGroupAsync(string managementGroupId, string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateDeleteAtManagementGroupRequest(managementGroupId, policyDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation deletes the policy definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy definition to delete. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response DeleteAtManagementGroup(string managementGroupId, string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateDeleteAtManagementGroupRequest(managementGroupId, policyDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetAtManagementGroupRequestUri(string managementGroupId, string policyDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetAtManagementGroupRequest(string managementGroupId, string policyDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions/", false); - uri.AppendPath(policyDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the policy definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy definition to get. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> GetAtManagementGroupAsync(string managementGroupId, string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateGetAtManagementGroupRequest(managementGroupId, policyDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicyDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the policy definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy definition to get. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response GetAtManagementGroup(string managementGroupId, string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var message = CreateGetAtManagementGroupRequest(managementGroupId, policyDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionData.DeserializePolicyDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicyDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri(string subscriptionId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - return uri; - } - - internal HttpMessage CreateListRequest(string subscriptionId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the policy definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListAsync(string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the policy definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response List(string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListBuiltInRequestUri(string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - return uri; - } - - internal HttpMessage CreateListBuiltInRequest(string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the built-in policy definitions that match the optional given $filter. If $filter='policyType -eq {value}' is provided, the returned list only includes all built-in policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy definitions whose category match the {value}. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - public async Task> ListBuiltInAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - using var message = CreateListBuiltInRequest(filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the built-in policy definitions that match the optional given $filter. If $filter='policyType -eq {value}' is provided, the returned list only includes all built-in policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy definitions whose category match the {value}. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - public Response ListBuiltIn(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - using var message = CreateListBuiltInRequest(filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListByManagementGroupRequestUri(string managementGroupId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - return uri; - } - - internal HttpMessage CreateListByManagementGroupRequest(string managementGroupId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policyDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the policy definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListByManagementGroupAsync(string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListByManagementGroupRequest(managementGroupId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the policy definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response ListByManagementGroup(string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListByManagementGroupRequest(managementGroupId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string subscriptionId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the policy definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListNextPageAsync(string nextLink, string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the policy definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListNextPage(string nextLink, string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListBuiltInNextPageRequestUri(string nextLink, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListBuiltInNextPageRequest(string nextLink, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the built-in policy definitions that match the optional given $filter. If $filter='policyType -eq {value}' is provided, the returned list only includes all built-in policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy definitions whose category match the {value}. - /// The URL to the next page of results. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - public async Task> ListBuiltInNextPageAsync(string nextLink, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListBuiltInNextPageRequest(nextLink, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the built-in policy definitions that match the optional given $filter. If $filter='policyType -eq {value}' is provided, the returned list only includes all built-in policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy definitions whose category match the {value}. - /// The URL to the next page of results. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - public Response ListBuiltInNextPage(string nextLink, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListBuiltInNextPageRequest(nextLink, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListByManagementGroupNextPageRequestUri(string nextLink, string managementGroupId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListByManagementGroupNextPageRequest(string nextLink, string managementGroupId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the policy definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// The URL to the next page of results. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListByManagementGroupNextPageAsync(string nextLink, string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListByManagementGroupNextPageRequest(nextLink, managementGroupId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the policy definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// The URL to the next page of results. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListByManagementGroupNextPage(string nextLink, string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListByManagementGroupNextPageRequest(nextLink, managementGroupId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicyDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicyDefinitionListResult.DeserializePolicyDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicySetDefinitionsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicySetDefinitionsRestOperations.cs deleted file mode 100644 index 74741a5519..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicySetDefinitionsRestOperations.cs +++ /dev/null @@ -1,1149 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class PolicySetDefinitionsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of PolicySetDefinitionsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public PolicySetDefinitionsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2021-06-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateCreateOrUpdateRequestUri(string subscriptionId, string policySetDefinitionName, PolicySetDefinitionData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string policySetDefinitionName, PolicySetDefinitionData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// This operation creates or updates a policy set definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy set definition to create. - /// The policy set definition properties. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> CreateOrUpdateAsync(string subscriptionId, string policySetDefinitionName, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateRequest(subscriptionId, policySetDefinitionName, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 201: - { - PolicySetDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation creates or updates a policy set definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy set definition to create. - /// The policy set definition properties. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response CreateOrUpdate(string subscriptionId, string policySetDefinitionName, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateRequest(subscriptionId, policySetDefinitionName, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 201: - { - PolicySetDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteRequestUri(string subscriptionId, string policySetDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteRequest(string subscriptionId, string policySetDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation deletes the policy set definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy set definition to delete. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task DeleteAsync(string subscriptionId, string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateDeleteRequest(subscriptionId, policySetDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation deletes the policy set definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy set definition to delete. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Delete(string subscriptionId, string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateDeleteRequest(subscriptionId, policySetDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetRequestUri(string subscriptionId, string policySetDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetRequest(string subscriptionId, string policySetDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the policy set definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> GetAsync(string subscriptionId, string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateGetRequest(subscriptionId, policySetDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicySetDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the policy set definition in the given subscription with the given name. - /// The ID of the target subscription. - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Get(string subscriptionId, string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateGetRequest(subscriptionId, policySetDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicySetDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetBuiltInRequestUri(string policySetDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetBuiltInRequest(string policySetDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the built-in policy set definition with the given name. - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetBuiltInAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateGetBuiltInRequest(policySetDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicySetDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the built-in policy set definition with the given name. - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response GetBuiltIn(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateGetBuiltInRequest(policySetDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicySetDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri(string subscriptionId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - return uri; - } - - internal HttpMessage CreateListRequest(string subscriptionId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the policy set definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListAsync(string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the policy set definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response List(string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListBuiltInRequestUri(string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - return uri; - } - - internal HttpMessage CreateListBuiltInRequest(string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the built-in policy set definitions that match the optional given $filter. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy set definitions whose category match the {value}. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - public async Task> ListBuiltInAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - using var message = CreateListBuiltInRequest(filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the built-in policy set definitions that match the optional given $filter. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy set definitions whose category match the {value}. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - public Response ListBuiltIn(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - using var message = CreateListBuiltInRequest(filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateCreateOrUpdateAtManagementGroupRequestUri(string managementGroupId, string policySetDefinitionName, PolicySetDefinitionData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateAtManagementGroupRequest(string managementGroupId, string policySetDefinitionName, PolicySetDefinitionData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// This operation creates or updates a policy set definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy set definition to create. - /// The policy set definition properties. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> CreateOrUpdateAtManagementGroupAsync(string managementGroupId, string policySetDefinitionName, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateAtManagementGroupRequest(managementGroupId, policySetDefinitionName, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 201: - { - PolicySetDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation creates or updates a policy set definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy set definition to create. - /// The policy set definition properties. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response CreateOrUpdateAtManagementGroup(string managementGroupId, string policySetDefinitionName, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateAtManagementGroupRequest(managementGroupId, policySetDefinitionName, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 201: - { - PolicySetDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteAtManagementGroupRequestUri(string managementGroupId, string policySetDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteAtManagementGroupRequest(string managementGroupId, string policySetDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation deletes the policy set definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy set definition to delete. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task DeleteAtManagementGroupAsync(string managementGroupId, string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateDeleteAtManagementGroupRequest(managementGroupId, policySetDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation deletes the policy set definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy set definition to delete. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response DeleteAtManagementGroup(string managementGroupId, string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateDeleteAtManagementGroupRequest(managementGroupId, policySetDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetAtManagementGroupRequestUri(string managementGroupId, string policySetDefinitionName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetAtManagementGroupRequest(string managementGroupId, string policySetDefinitionName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions/", false); - uri.AppendPath(policySetDefinitionName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves the policy set definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> GetAtManagementGroupAsync(string managementGroupId, string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateGetAtManagementGroupRequest(managementGroupId, policySetDefinitionName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicySetDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves the policy set definition in the given management group with the given name. - /// The ID of the management group. - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response GetAtManagementGroup(string managementGroupId, string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var message = CreateGetAtManagementGroupRequest(managementGroupId, policySetDefinitionName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionData.DeserializePolicySetDefinitionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((PolicySetDefinitionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListByManagementGroupRequestUri(string managementGroupId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - return uri; - } - - internal HttpMessage CreateListByManagementGroupRequest(string managementGroupId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Management/managementGroups/", false); - uri.AppendPath(managementGroupId, true); - uri.AppendPath("/providers/Microsoft.Authorization/policySetDefinitions", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (filter != null) - { - uri.AppendQuery("$filter", filter, false); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the policy set definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListByManagementGroupAsync(string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListByManagementGroupRequest(managementGroupId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the policy set definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response ListByManagementGroup(string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListByManagementGroupRequest(managementGroupId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string subscriptionId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the policy set definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListNextPageAsync(string nextLink, string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the policy set definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListNextPage(string nextLink, string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListBuiltInNextPageRequestUri(string nextLink, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListBuiltInNextPageRequest(string nextLink, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the built-in policy set definitions that match the optional given $filter. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy set definitions whose category match the {value}. - /// The URL to the next page of results. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - public async Task> ListBuiltInNextPageAsync(string nextLink, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListBuiltInNextPageRequest(nextLink, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the built-in policy set definitions that match the optional given $filter. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy set definitions whose category match the {value}. - /// The URL to the next page of results. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// is null. - public Response ListBuiltInNextPage(string nextLink, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListBuiltInNextPageRequest(nextLink, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListByManagementGroupNextPageRequestUri(string nextLink, string managementGroupId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListByManagementGroupNextPageRequest(string nextLink, string managementGroupId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation retrieves a list of all the policy set definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// The URL to the next page of results. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListByManagementGroupNextPageAsync(string nextLink, string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListByManagementGroupNextPageRequest(nextLink, managementGroupId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation retrieves a list of all the policy set definitions in a given management group that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the management group, including those that apply directly or from management groups that contain the given management group. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given management group. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// The URL to the next page of results. - /// The ID of the management group. - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListByManagementGroupNextPage(string nextLink, string managementGroupId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(managementGroupId, nameof(managementGroupId)); - - using var message = CreateListByManagementGroupNextPageRequest(nextLink, managementGroupId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PolicySetDefinitionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PolicySetDefinitionListResult.DeserializePolicySetDefinitionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ProviderResourceTypesRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ProviderResourceTypesRestOperations.cs deleted file mode 100644 index 3acae9da9e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ProviderResourceTypesRestOperations.cs +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class ProviderResourceTypesRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of ProviderResourceTypesRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public ProviderResourceTypesRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2022-09-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateListRequestUri(string subscriptionId, string resourceProviderNamespace, string expand) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/resourceTypes", false); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListRequest(string subscriptionId, string resourceProviderNamespace, string expand) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/resourceTypes", false); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// List the resource types for a specified resource provider. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> ListAsync(string subscriptionId, string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateListRequest(subscriptionId, resourceProviderNamespace, expand); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ProviderResourceTypeListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ProviderResourceTypeListResult.DeserializeProviderResourceTypeListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// List the resource types for a specified resource provider. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response List(string subscriptionId, string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateListRequest(subscriptionId, resourceProviderNamespace, expand); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ProviderResourceTypeListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ProviderResourceTypeListResult.DeserializeProviderResourceTypeListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ProvidersRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ProvidersRestOperations.cs deleted file mode 100644 index 63f444d6e3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ProvidersRestOperations.cs +++ /dev/null @@ -1,802 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class ProvidersRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of ProvidersRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public ProvidersRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2022-09-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateUnregisterRequestUri(string subscriptionId, string resourceProviderNamespace) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/unregister", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateUnregisterRequest(string subscriptionId, string resourceProviderNamespace) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/unregister", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Unregisters a subscription from a resource provider. - /// The ID of the target subscription. - /// The namespace of the resource provider to unregister. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> UnregisterAsync(string subscriptionId, string resourceProviderNamespace, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateUnregisterRequest(subscriptionId, resourceProviderNamespace); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceProviderData.DeserializeResourceProviderData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Unregisters a subscription from a resource provider. - /// The ID of the target subscription. - /// The namespace of the resource provider to unregister. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Unregister(string subscriptionId, string resourceProviderNamespace, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateUnregisterRequest(subscriptionId, resourceProviderNamespace); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceProviderData.DeserializeResourceProviderData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateProviderPermissionsRequestUri(string subscriptionId, string resourceProviderNamespace) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/providerPermissions", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateProviderPermissionsRequest(string subscriptionId, string resourceProviderNamespace) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/providerPermissions", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Get the provider permissions. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> ProviderPermissionsAsync(string subscriptionId, string resourceProviderNamespace, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateProviderPermissionsRequest(subscriptionId, resourceProviderNamespace); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ProviderPermissionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ProviderPermissionListResult.DeserializeProviderPermissionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Get the provider permissions. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response ProviderPermissions(string subscriptionId, string resourceProviderNamespace, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateProviderPermissionsRequest(subscriptionId, resourceProviderNamespace); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ProviderPermissionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ProviderPermissionListResult.DeserializeProviderPermissionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateRegisterRequestUri(string subscriptionId, string resourceProviderNamespace, ProviderRegistrationContent content) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/register", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateRegisterRequest(string subscriptionId, string resourceProviderNamespace, ProviderRegistrationContent content) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - uri.AppendPath("/register", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - if (content != null) - { - request.Headers.Add("Content-Type", "application/json"); - var content0 = new Utf8JsonRequestContent(); - content0.JsonWriter.WriteObjectValue(content, ModelSerializationExtensions.WireOptions); - request.Content = content0; - } - _userAgent.Apply(message); - return message; - } - - /// Registers a subscription with a resource provider. - /// The ID of the target subscription. - /// The namespace of the resource provider to register. - /// The third party consent for S2S. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> RegisterAsync(string subscriptionId, string resourceProviderNamespace, ProviderRegistrationContent content = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateRegisterRequest(subscriptionId, resourceProviderNamespace, content); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceProviderData.DeserializeResourceProviderData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Registers a subscription with a resource provider. - /// The ID of the target subscription. - /// The namespace of the resource provider to register. - /// The third party consent for S2S. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Register(string subscriptionId, string resourceProviderNamespace, ProviderRegistrationContent content = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateRegisterRequest(subscriptionId, resourceProviderNamespace, content); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceProviderData.DeserializeResourceProviderData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri(string subscriptionId, string expand) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers", false); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListRequest(string subscriptionId, string expand) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers", false); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all resource providers for a subscription. - /// The ID of the target subscription. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListAsync(string subscriptionId, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, expand); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceProviderListResult.DeserializeResourceProviderListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all resource providers for a subscription. - /// The ID of the target subscription. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response List(string subscriptionId, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, expand); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceProviderListResult.DeserializeResourceProviderListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListAtTenantScopeRequestUri(string expand) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers", false); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListAtTenantScopeRequest(string expand) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers", false); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all resource providers for the tenant. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - public async Task> ListAtTenantScopeAsync(string expand = null, CancellationToken cancellationToken = default) - { - using var message = CreateListAtTenantScopeRequest(expand); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - TenantResourceProviderListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = TenantResourceProviderListResult.DeserializeTenantResourceProviderListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all resource providers for the tenant. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - public Response ListAtTenantScope(string expand = null, CancellationToken cancellationToken = default) - { - using var message = CreateListAtTenantScopeRequest(expand); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - TenantResourceProviderListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = TenantResourceProviderListResult.DeserializeTenantResourceProviderListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetRequestUri(string subscriptionId, string resourceProviderNamespace, string expand) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetRequest(string subscriptionId, string resourceProviderNamespace, string expand) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets the specified resource provider. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> GetAsync(string subscriptionId, string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateGetRequest(subscriptionId, resourceProviderNamespace, expand); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceProviderData.DeserializeResourceProviderData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ResourceProviderData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets the specified resource provider. - /// The ID of the target subscription. - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Get(string subscriptionId, string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateGetRequest(subscriptionId, resourceProviderNamespace, expand); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceProviderData.DeserializeResourceProviderData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ResourceProviderData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetAtTenantScopeRequestUri(string resourceProviderNamespace, string expand) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetAtTenantScopeRequest(string resourceProviderNamespace, string expand) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/", false); - uri.AppendPath(resourceProviderNamespace, true); - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets the specified resource provider at the tenant level. - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetAtTenantScopeAsync(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateGetAtTenantScopeRequest(resourceProviderNamespace, expand); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - TenantResourceProvider value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = TenantResourceProvider.DeserializeTenantResourceProvider(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets the specified resource provider at the tenant level. - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response GetAtTenantScope(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var message = CreateGetAtTenantScopeRequest(resourceProviderNamespace, expand); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - TenantResourceProvider value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = TenantResourceProvider.DeserializeTenantResourceProvider(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string subscriptionId, string expand) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string expand) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all resource providers for a subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListNextPageAsync(string nextLink, string subscriptionId, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, expand); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceProviderListResult.DeserializeResourceProviderListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all resource providers for a subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListNextPage(string nextLink, string subscriptionId, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, expand); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceProviderListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceProviderListResult.DeserializeResourceProviderListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListAtTenantScopeNextPageRequestUri(string nextLink, string expand) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListAtTenantScopeNextPageRequest(string nextLink, string expand) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all resource providers for the tenant. - /// The URL to the next page of results. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - public async Task> ListAtTenantScopeNextPageAsync(string nextLink, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListAtTenantScopeNextPageRequest(nextLink, expand); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - TenantResourceProviderListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = TenantResourceProviderListResult.DeserializeTenantResourceProviderListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all resource providers for the tenant. - /// The URL to the next page of results. - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - public Response ListAtTenantScopeNextPage(string nextLink, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListAtTenantScopeNextPageRequest(nextLink, expand); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - TenantResourceProviderListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = TenantResourceProviderListResult.DeserializeTenantResourceProviderListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourceGroupsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourceGroupsRestOperations.cs deleted file mode 100644 index 06b9758562..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourceGroupsRestOperations.cs +++ /dev/null @@ -1,663 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class ResourceGroupsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of ResourceGroupsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public ResourceGroupsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2022-09-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateCreateOrUpdateRequestUri(string subscriptionId, string resourceGroupName, ResourceGroupData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, ResourceGroupData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// Creates or updates a resource group. - /// The ID of the target subscription. - /// The name of the resource group to create or update. Can include alphanumeric, underscore, parentheses, hyphen, period (except at end), and Unicode characters that match the allowed characters. - /// Parameters supplied to the create or update a resource group. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> CreateOrUpdateAsync(string subscriptionId, string resourceGroupName, ResourceGroupData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 201: - { - ResourceGroupData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceGroupData.DeserializeResourceGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Creates or updates a resource group. - /// The ID of the target subscription. - /// The name of the resource group to create or update. Can include alphanumeric, underscore, parentheses, hyphen, period (except at end), and Unicode characters that match the allowed characters. - /// Parameters supplied to the create or update a resource group. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response CreateOrUpdate(string subscriptionId, string resourceGroupName, ResourceGroupData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 201: - { - ResourceGroupData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceGroupData.DeserializeResourceGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteRequestUri(string subscriptionId, string resourceGroupName, string forceDeletionTypes) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - if (forceDeletionTypes != null) - { - uri.AppendQuery("forceDeletionTypes", forceDeletionTypes, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string forceDeletionTypes) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - if (forceDeletionTypes != null) - { - uri.AppendQuery("forceDeletionTypes", forceDeletionTypes, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// When you delete a resource group, all of its resources are also deleted. Deleting a resource group deletes all of its template deployments and currently stored operations. - /// The ID of the target subscription. - /// The name of the resource group to delete. The name is case insensitive. - /// The resource types you want to force delete. Currently, only the following is supported: forceDeletionTypes=Microsoft.Compute/virtualMachines,Microsoft.Compute/virtualMachineScaleSets. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task DeleteAsync(string subscriptionId, string resourceGroupName, string forceDeletionTypes = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, forceDeletionTypes); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// When you delete a resource group, all of its resources are also deleted. Deleting a resource group deletes all of its template deployments and currently stored operations. - /// The ID of the target subscription. - /// The name of the resource group to delete. The name is case insensitive. - /// The resource types you want to force delete. Currently, only the following is supported: forceDeletionTypes=Microsoft.Compute/virtualMachines,Microsoft.Compute/virtualMachineScaleSets. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Delete(string subscriptionId, string resourceGroupName, string forceDeletionTypes = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, forceDeletionTypes); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetRequestUri(string subscriptionId, string resourceGroupName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets a resource group. - /// The ID of the target subscription. - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> GetAsync(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateGetRequest(subscriptionId, resourceGroupName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceGroupData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceGroupData.DeserializeResourceGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ResourceGroupData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets a resource group. - /// The ID of the target subscription. - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Get(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateGetRequest(subscriptionId, resourceGroupName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceGroupData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceGroupData.DeserializeResourceGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((ResourceGroupData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateUpdateRequestUri(string subscriptionId, string resourceGroupName, ResourceGroupPatch patch) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateUpdateRequest(string subscriptionId, string resourceGroupName, ResourceGroupPatch patch) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Patch; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(patch, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// Resource groups can be updated through a simple PATCH operation to a group address. The format of the request is the same as that for creating a resource group. If a field is unspecified, the current value is retained. - /// The ID of the target subscription. - /// The name of the resource group to update. The name is case insensitive. - /// Parameters supplied to update a resource group. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> UpdateAsync(string subscriptionId, string resourceGroupName, ResourceGroupPatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNull(patch, nameof(patch)); - - using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, patch); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceGroupData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceGroupData.DeserializeResourceGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Resource groups can be updated through a simple PATCH operation to a group address. The format of the request is the same as that for creating a resource group. If a field is unspecified, the current value is retained. - /// The ID of the target subscription. - /// The name of the resource group to update. The name is case insensitive. - /// Parameters supplied to update a resource group. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Update(string subscriptionId, string resourceGroupName, ResourceGroupPatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNull(patch, nameof(patch)); - - using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, patch); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceGroupData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceGroupData.DeserializeResourceGroupData(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateExportTemplateRequestUri(string subscriptionId, string resourceGroupName, ExportTemplate exportTemplate) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendPath("/exportTemplate", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateExportTemplateRequest(string subscriptionId, string resourceGroupName, ExportTemplate exportTemplate) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendPath("/exportTemplate", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(exportTemplate, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// Captures the specified resource group as a template. - /// The ID of the target subscription. - /// The name of the resource group. The name is case insensitive. - /// Parameters for exporting the template. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task ExportTemplateAsync(string subscriptionId, string resourceGroupName, ExportTemplate exportTemplate, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNull(exportTemplate, nameof(exportTemplate)); - - using var message = CreateExportTemplateRequest(subscriptionId, resourceGroupName, exportTemplate); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// Captures the specified resource group as a template. - /// The ID of the target subscription. - /// The name of the resource group. The name is case insensitive. - /// Parameters for exporting the template. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response ExportTemplate(string subscriptionId, string resourceGroupName, ExportTemplate exportTemplate, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - Argument.AssertNotNull(exportTemplate, nameof(exportTemplate)); - - using var message = CreateExportTemplateRequest(subscriptionId, resourceGroupName, exportTemplate); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri(string subscriptionId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListRequest(string subscriptionId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourcegroups", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all the resource groups for a subscription. - /// The ID of the target subscription. - /// The filter to apply on the operation.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. - /// The number of results to return. If null is passed, returns all resource groups. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListAsync(string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceGroupListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceGroupListResult.DeserializeResourceGroupListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all the resource groups for a subscription. - /// The ID of the target subscription. - /// The filter to apply on the operation.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. - /// The number of results to return. If null is passed, returns all resource groups. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response List(string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceGroupListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceGroupListResult.DeserializeResourceGroupListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string subscriptionId, string filter, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string filter, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all the resource groups for a subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. - /// The number of results to return. If null is passed, returns all resource groups. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListNextPageAsync(string nextLink, string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceGroupListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceGroupListResult.DeserializeResourceGroupListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all the resource groups for a subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. - /// The number of results to return. If null is passed, returns all resource groups. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListNextPage(string nextLink, string subscriptionId, string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceGroupListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceGroupListResult.DeserializeResourceGroupListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourceManagementRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourceManagementRestOperations.cs deleted file mode 100644 index 490f691f55..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourceManagementRestOperations.cs +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class ResourceManagementRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of ResourceManagementRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public ResourceManagementRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2022-12-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateCheckResourceNameRequestUri(ResourceNameValidationContent content) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Resources/checkResourceName", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCheckResourceNameRequest(ResourceNameValidationContent content) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/providers/Microsoft.Resources/checkResourceName", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - if (content != null) - { - request.Headers.Add("Content-Type", "application/json"); - var content0 = new Utf8JsonRequestContent(); - content0.JsonWriter.WriteObjectValue(content, ModelSerializationExtensions.WireOptions); - request.Content = content0; - } - _userAgent.Apply(message); - return message; - } - - /// A resource name is valid if it is not a reserved word, does not contains a reserved word and does not start with a reserved word. - /// Resource object with values for resource name and resource type. - /// The cancellation token to use. - public async Task> CheckResourceNameAsync(ResourceNameValidationContent content = null, CancellationToken cancellationToken = default) - { - using var message = CreateCheckResourceNameRequest(content); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceNameValidationResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceNameValidationResult.DeserializeResourceNameValidationResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// A resource name is valid if it is not a reserved word, does not contains a reserved word and does not start with a reserved word. - /// Resource object with values for resource name and resource type. - /// The cancellation token to use. - public Response CheckResourceName(ResourceNameValidationContent content = null, CancellationToken cancellationToken = default) - { - using var message = CreateCheckResourceNameRequest(content); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceNameValidationResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceNameValidationResult.DeserializeResourceNameValidationResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourcesRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourcesRestOperations.cs deleted file mode 100644 index c990c23b40..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourcesRestOperations.cs +++ /dev/null @@ -1,915 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class ResourcesRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of ResourcesRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public ResourcesRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2022-09-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateListByResourceGroupRequestUri(string subscriptionId, string resourceGroupName, string filter, string expand, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendPath("/resources", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListByResourceGroupRequest(string subscriptionId, string resourceGroupName, string filter, string expand, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(resourceGroupName, true); - uri.AppendPath("/resources", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Get all the resources for a resource group. - /// The ID of the target subscription. - /// The resource group with the resources to get. - /// The filter to apply on the operation.<br><br>The properties you can use for eq (equals) or ne (not equals) are: location, resourceType, name, resourceGroup, identity, identity/principalId, plan, plan/publisher, plan/product, plan/name, plan/version, and plan/promotionCode.<br><br>For example, to filter by a resource type, use: $filter=resourceType eq 'Microsoft.Network/virtualNetworks'<br><br>You can use substringof(value, property) in the filter. The properties you can use for substring are: name and resourceGroup.<br><br>For example, to get all resources with 'demo' anywhere in the name, use: $filter=substringof('demo', name)<br><br>You can link more than one substringof together by adding and/or operators.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. When you filter by a tag name and value, the tags for each resource are not returned in the results.<br><br>You can use some properties together when filtering. The combinations you can use are: substringof and/or resourceType, plan and plan/publisher and plan/name, identity and identity/principalId. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of results to return. If null is passed, returns all resources. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> ListByResourceGroupAsync(string subscriptionId, string resourceGroupName, string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName, filter, expand, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceListResult.DeserializeResourceListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Get all the resources for a resource group. - /// The ID of the target subscription. - /// The resource group with the resources to get. - /// The filter to apply on the operation.<br><br>The properties you can use for eq (equals) or ne (not equals) are: location, resourceType, name, resourceGroup, identity, identity/principalId, plan, plan/publisher, plan/product, plan/name, plan/version, and plan/promotionCode.<br><br>For example, to filter by a resource type, use: $filter=resourceType eq 'Microsoft.Network/virtualNetworks'<br><br>You can use substringof(value, property) in the filter. The properties you can use for substring are: name and resourceGroup.<br><br>For example, to get all resources with 'demo' anywhere in the name, use: $filter=substringof('demo', name)<br><br>You can link more than one substringof together by adding and/or operators.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. When you filter by a tag name and value, the tags for each resource are not returned in the results.<br><br>You can use some properties together when filtering. The combinations you can use are: substringof and/or resourceType, plan and plan/publisher and plan/name, identity and identity/principalId. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of results to return. If null is passed, returns all resources. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response ListByResourceGroup(string subscriptionId, string resourceGroupName, string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName, filter, expand, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceListResult.DeserializeResourceListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateMoveResourcesRequestUri(string subscriptionId, string sourceResourceGroupName, ResourcesMoveContent content) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(sourceResourceGroupName, true); - uri.AppendPath("/moveResources", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateMoveResourcesRequest(string subscriptionId, string sourceResourceGroupName, ResourcesMoveContent content) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(sourceResourceGroupName, true); - uri.AppendPath("/moveResources", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content0 = new Utf8JsonRequestContent(); - content0.JsonWriter.WriteObjectValue(content, ModelSerializationExtensions.WireOptions); - request.Content = content0; - _userAgent.Apply(message); - return message; - } - - /// The resources to be moved must be in the same source resource group in the source subscription being used. The target resource group may be in a different subscription. When moving resources, both the source group and the target group are locked for the duration of the operation. Write and delete operations are blocked on the groups until the move completes. - /// The ID of the target subscription. - /// The name of the resource group from the source subscription containing the resources to be moved. - /// Parameters for moving resources. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task MoveResourcesAsync(string subscriptionId, string sourceResourceGroupName, ResourcesMoveContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(sourceResourceGroupName, nameof(sourceResourceGroupName)); - Argument.AssertNotNull(content, nameof(content)); - - using var message = CreateMoveResourcesRequest(subscriptionId, sourceResourceGroupName, content); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 202: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// The resources to be moved must be in the same source resource group in the source subscription being used. The target resource group may be in a different subscription. When moving resources, both the source group and the target group are locked for the duration of the operation. Write and delete operations are blocked on the groups until the move completes. - /// The ID of the target subscription. - /// The name of the resource group from the source subscription containing the resources to be moved. - /// Parameters for moving resources. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response MoveResources(string subscriptionId, string sourceResourceGroupName, ResourcesMoveContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(sourceResourceGroupName, nameof(sourceResourceGroupName)); - Argument.AssertNotNull(content, nameof(content)); - - using var message = CreateMoveResourcesRequest(subscriptionId, sourceResourceGroupName, content); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 202: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateValidateMoveResourcesRequestUri(string subscriptionId, string sourceResourceGroupName, ResourcesMoveContent content) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(sourceResourceGroupName, true); - uri.AppendPath("/validateMoveResources", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateValidateMoveResourcesRequest(string subscriptionId, string sourceResourceGroupName, ResourcesMoveContent content) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resourceGroups/", false); - uri.AppendPath(sourceResourceGroupName, true); - uri.AppendPath("/validateMoveResources", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content0 = new Utf8JsonRequestContent(); - content0.JsonWriter.WriteObjectValue(content, ModelSerializationExtensions.WireOptions); - request.Content = content0; - _userAgent.Apply(message); - return message; - } - - /// This operation checks whether the specified resources can be moved to the target. The resources to be moved must be in the same source resource group in the source subscription being used. The target resource group may be in a different subscription. If validation succeeds, it returns HTTP response code 204 (no content). If validation fails, it returns HTTP response code 409 (Conflict) with an error message. Retrieve the URL in the Location header value to check the result of the long-running operation. - /// The ID of the target subscription. - /// The name of the resource group from the source subscription containing the resources to be validated for move. - /// Parameters for moving resources. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task ValidateMoveResourcesAsync(string subscriptionId, string sourceResourceGroupName, ResourcesMoveContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(sourceResourceGroupName, nameof(sourceResourceGroupName)); - Argument.AssertNotNull(content, nameof(content)); - - using var message = CreateValidateMoveResourcesRequest(subscriptionId, sourceResourceGroupName, content); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 202: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation checks whether the specified resources can be moved to the target. The resources to be moved must be in the same source resource group in the source subscription being used. The target resource group may be in a different subscription. If validation succeeds, it returns HTTP response code 204 (no content). If validation fails, it returns HTTP response code 409 (Conflict) with an error message. Retrieve the URL in the Location header value to check the result of the long-running operation. - /// The ID of the target subscription. - /// The name of the resource group from the source subscription containing the resources to be validated for move. - /// Parameters for moving resources. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response ValidateMoveResources(string subscriptionId, string sourceResourceGroupName, ResourcesMoveContent content, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(sourceResourceGroupName, nameof(sourceResourceGroupName)); - Argument.AssertNotNull(content, nameof(content)); - - using var message = CreateValidateMoveResourcesRequest(subscriptionId, sourceResourceGroupName, content); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 202: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri(string subscriptionId, string filter, string expand, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resources", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListRequest(string subscriptionId, string filter, string expand, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/resources", false); - if (filter != null) - { - uri.AppendQuery("$filter", filter, true); - } - if (expand != null) - { - uri.AppendQuery("$expand", expand, true); - } - if (top != null) - { - uri.AppendQuery("$top", top.Value, true); - } - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Get all the resources in a subscription. - /// The ID of the target subscription. - /// The filter to apply on the operation.<br><br>Filter comparison operators include `eq` (equals) and `ne` (not equals) and may be used with the following properties: `location`, `resourceType`, `name`, `resourceGroup`, `identity`, `identity/principalId`, `plan`, `plan/publisher`, `plan/product`, `plan/name`, `plan/version`, and `plan/promotionCode`.<br><br>For example, to filter by a resource type, use `$filter=resourceType eq 'Microsoft.Network/virtualNetworks'`<br><br><br>`substringof(value, property)` can be used to filter for substrings of the following currently-supported properties: `name` and `resourceGroup`<br><br>For example, to get all resources with 'demo' anywhere in the resource name, use `$filter=substringof('demo', name)`<br><br>Multiple substring operations can also be combined using `and`/`or` operators.<br><br>Note that any truncated number of results queried via `$top` may also not be compatible when using a filter.<br><br><br>Resources can be filtered by tag names and values. For example, to filter for a tag name and value, use `$filter=tagName eq 'tag1' and tagValue eq 'Value1'`. Note that when resources are filtered by tag name and value, <b>the original tags for each resource will not be returned in the results.</b> Any list of additional properties queried via `$expand` may also not be compatible when filtering by tag names/values. <br><br>For tag names only, resources can be filtered by prefix using the following syntax: `$filter=startswith(tagName, 'depart')`. This query will return all resources with a tag name prefixed by the phrase `depart` (i.e.`department`, `departureDate`, `departureTime`, etc.)<br><br><br>Note that some properties can be combined when filtering resources, which include the following: `substringof() and/or resourceType`, `plan and plan/publisher and plan/name`, and `identity and identity/principalId`. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of recommendations per page if a paged version of this API is being used. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListAsync(string subscriptionId, string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, expand, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceListResult.DeserializeResourceListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Get all the resources in a subscription. - /// The ID of the target subscription. - /// The filter to apply on the operation.<br><br>Filter comparison operators include `eq` (equals) and `ne` (not equals) and may be used with the following properties: `location`, `resourceType`, `name`, `resourceGroup`, `identity`, `identity/principalId`, `plan`, `plan/publisher`, `plan/product`, `plan/name`, `plan/version`, and `plan/promotionCode`.<br><br>For example, to filter by a resource type, use `$filter=resourceType eq 'Microsoft.Network/virtualNetworks'`<br><br><br>`substringof(value, property)` can be used to filter for substrings of the following currently-supported properties: `name` and `resourceGroup`<br><br>For example, to get all resources with 'demo' anywhere in the resource name, use `$filter=substringof('demo', name)`<br><br>Multiple substring operations can also be combined using `and`/`or` operators.<br><br>Note that any truncated number of results queried via `$top` may also not be compatible when using a filter.<br><br><br>Resources can be filtered by tag names and values. For example, to filter for a tag name and value, use `$filter=tagName eq 'tag1' and tagValue eq 'Value1'`. Note that when resources are filtered by tag name and value, <b>the original tags for each resource will not be returned in the results.</b> Any list of additional properties queried via `$expand` may also not be compatible when filtering by tag names/values. <br><br>For tag names only, resources can be filtered by prefix using the following syntax: `$filter=startswith(tagName, 'depart')`. This query will return all resources with a tag name prefixed by the phrase `depart` (i.e.`department`, `departureDate`, `departureTime`, etc.)<br><br><br>Note that some properties can be combined when filtering resources, which include the following: `substringof() and/or resourceType`, `plan and plan/publisher and plan/name`, and `identity and identity/principalId`. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of recommendations per page if a paged version of this API is being used. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response List(string subscriptionId, string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId, filter, expand, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceListResult.DeserializeResourceListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteByIdRequestUri(string resourceId, string apiVersion) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(resourceId, false); - uri.AppendQuery("api-version", apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteByIdRequest(string resourceId, string apiVersion) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(resourceId, false); - uri.AppendQuery("api-version", apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Deletes a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The API version to use for the operation. - /// The cancellation token to use. - /// or is null. - public async Task DeleteByIdAsync(string resourceId, string apiVersion, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(resourceId, nameof(resourceId)); - Argument.AssertNotNull(apiVersion, nameof(apiVersion)); - - using var message = CreateDeleteByIdRequest(resourceId, apiVersion); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 202: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// Deletes a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The API version to use for the operation. - /// The cancellation token to use. - /// or is null. - public Response DeleteById(string resourceId, string apiVersion, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(resourceId, nameof(resourceId)); - Argument.AssertNotNull(apiVersion, nameof(apiVersion)); - - using var message = CreateDeleteByIdRequest(resourceId, apiVersion); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 202: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateCreateOrUpdateByIdRequestUri(string resourceId, string apiVersion, GenericResourceData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(resourceId, false); - uri.AppendQuery("api-version", apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateByIdRequest(string resourceId, string apiVersion, GenericResourceData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(resourceId, false); - uri.AppendQuery("api-version", apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// Create a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The API version to use for the operation. - /// Create or update resource parameters. - /// The cancellation token to use. - /// , or is null. - public async Task CreateOrUpdateByIdAsync(string resourceId, string apiVersion, GenericResourceData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(resourceId, nameof(resourceId)); - Argument.AssertNotNull(apiVersion, nameof(apiVersion)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateByIdRequest(resourceId, apiVersion, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 201: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// Create a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The API version to use for the operation. - /// Create or update resource parameters. - /// The cancellation token to use. - /// , or is null. - public Response CreateOrUpdateById(string resourceId, string apiVersion, GenericResourceData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(resourceId, nameof(resourceId)); - Argument.AssertNotNull(apiVersion, nameof(apiVersion)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateByIdRequest(resourceId, apiVersion, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 201: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateUpdateByIdRequestUri(string resourceId, string apiVersion, GenericResourceData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(resourceId, false); - uri.AppendQuery("api-version", apiVersion, true); - return uri; - } - - internal HttpMessage CreateUpdateByIdRequest(string resourceId, string apiVersion, GenericResourceData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Patch; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(resourceId, false); - uri.AppendQuery("api-version", apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// Updates a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The API version to use for the operation. - /// Update resource parameters. - /// The cancellation token to use. - /// , or is null. - public async Task UpdateByIdAsync(string resourceId, string apiVersion, GenericResourceData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(resourceId, nameof(resourceId)); - Argument.AssertNotNull(apiVersion, nameof(apiVersion)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateUpdateByIdRequest(resourceId, apiVersion, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// Updates a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The API version to use for the operation. - /// Update resource parameters. - /// The cancellation token to use. - /// , or is null. - public Response UpdateById(string resourceId, string apiVersion, GenericResourceData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(resourceId, nameof(resourceId)); - Argument.AssertNotNull(apiVersion, nameof(apiVersion)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateUpdateByIdRequest(resourceId, apiVersion, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetByIdRequestUri(string resourceId, string apiVersion) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(resourceId, false); - uri.AppendQuery("api-version", apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetByIdRequest(string resourceId, string apiVersion) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(resourceId, false); - uri.AppendQuery("api-version", apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The API version to use for the operation. - /// The cancellation token to use. - /// or is null. - public async Task> GetByIdAsync(string resourceId, string apiVersion, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(resourceId, nameof(resourceId)); - Argument.AssertNotNull(apiVersion, nameof(apiVersion)); - - using var message = CreateGetByIdRequest(resourceId, apiVersion); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - GenericResourceData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = GenericResourceData.DeserializeGenericResourceData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((GenericResourceData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets a resource by ID. - /// The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}. - /// The API version to use for the operation. - /// The cancellation token to use. - /// or is null. - public Response GetById(string resourceId, string apiVersion, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(resourceId, nameof(resourceId)); - Argument.AssertNotNull(apiVersion, nameof(apiVersion)); - - using var message = CreateGetByIdRequest(resourceId, apiVersion); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - GenericResourceData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = GenericResourceData.DeserializeGenericResourceData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((GenericResourceData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListByResourceGroupNextPageRequestUri(string nextLink, string subscriptionId, string resourceGroupName, string filter, string expand, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListByResourceGroupNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string filter, string expand, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Get all the resources for a resource group. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The resource group with the resources to get. - /// The filter to apply on the operation.<br><br>The properties you can use for eq (equals) or ne (not equals) are: location, resourceType, name, resourceGroup, identity, identity/principalId, plan, plan/publisher, plan/product, plan/name, plan/version, and plan/promotionCode.<br><br>For example, to filter by a resource type, use: $filter=resourceType eq 'Microsoft.Network/virtualNetworks'<br><br>You can use substringof(value, property) in the filter. The properties you can use for substring are: name and resourceGroup.<br><br>For example, to get all resources with 'demo' anywhere in the name, use: $filter=substringof('demo', name)<br><br>You can link more than one substringof together by adding and/or operators.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. When you filter by a tag name and value, the tags for each resource are not returned in the results.<br><br>You can use some properties together when filtering. The combinations you can use are: substringof and/or resourceType, plan and plan/publisher and plan/name, identity and identity/principalId. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of results to return. If null is passed, returns all resources. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> ListByResourceGroupNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName, filter, expand, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceListResult.DeserializeResourceListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Get all the resources for a resource group. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The resource group with the resources to get. - /// The filter to apply on the operation.<br><br>The properties you can use for eq (equals) or ne (not equals) are: location, resourceType, name, resourceGroup, identity, identity/principalId, plan, plan/publisher, plan/product, plan/name, plan/version, and plan/promotionCode.<br><br>For example, to filter by a resource type, use: $filter=resourceType eq 'Microsoft.Network/virtualNetworks'<br><br>You can use substringof(value, property) in the filter. The properties you can use for substring are: name and resourceGroup.<br><br>For example, to get all resources with 'demo' anywhere in the name, use: $filter=substringof('demo', name)<br><br>You can link more than one substringof together by adding and/or operators.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. When you filter by a tag name and value, the tags for each resource are not returned in the results.<br><br>You can use some properties together when filtering. The combinations you can use are: substringof and/or resourceType, plan and plan/publisher and plan/name, identity and identity/principalId. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of results to return. If null is passed, returns all resources. - /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public Response ListByResourceGroupNextPage(string nextLink, string subscriptionId, string resourceGroupName, string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); - - using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName, filter, expand, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceListResult.DeserializeResourceListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string subscriptionId, string filter, string expand, int? top) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string filter, string expand, int? top) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Get all the resources in a subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation.<br><br>Filter comparison operators include `eq` (equals) and `ne` (not equals) and may be used with the following properties: `location`, `resourceType`, `name`, `resourceGroup`, `identity`, `identity/principalId`, `plan`, `plan/publisher`, `plan/product`, `plan/name`, `plan/version`, and `plan/promotionCode`.<br><br>For example, to filter by a resource type, use `$filter=resourceType eq 'Microsoft.Network/virtualNetworks'`<br><br><br>`substringof(value, property)` can be used to filter for substrings of the following currently-supported properties: `name` and `resourceGroup`<br><br>For example, to get all resources with 'demo' anywhere in the resource name, use `$filter=substringof('demo', name)`<br><br>Multiple substring operations can also be combined using `and`/`or` operators.<br><br>Note that any truncated number of results queried via `$top` may also not be compatible when using a filter.<br><br><br>Resources can be filtered by tag names and values. For example, to filter for a tag name and value, use `$filter=tagName eq 'tag1' and tagValue eq 'Value1'`. Note that when resources are filtered by tag name and value, <b>the original tags for each resource will not be returned in the results.</b> Any list of additional properties queried via `$expand` may also not be compatible when filtering by tag names/values. <br><br>For tag names only, resources can be filtered by prefix using the following syntax: `$filter=startswith(tagName, 'depart')`. This query will return all resources with a tag name prefixed by the phrase `depart` (i.e.`department`, `departureDate`, `departureTime`, etc.)<br><br><br>Note that some properties can be combined when filtering resources, which include the following: `substringof() and/or resourceType`, `plan and plan/publisher and plan/name`, and `identity and identity/principalId`. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of recommendations per page if a paged version of this API is being used. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListNextPageAsync(string nextLink, string subscriptionId, string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, expand, top); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - ResourceListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = ResourceListResult.DeserializeResourceListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Get all the resources in a subscription. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The filter to apply on the operation.<br><br>Filter comparison operators include `eq` (equals) and `ne` (not equals) and may be used with the following properties: `location`, `resourceType`, `name`, `resourceGroup`, `identity`, `identity/principalId`, `plan`, `plan/publisher`, `plan/product`, `plan/name`, `plan/version`, and `plan/promotionCode`.<br><br>For example, to filter by a resource type, use `$filter=resourceType eq 'Microsoft.Network/virtualNetworks'`<br><br><br>`substringof(value, property)` can be used to filter for substrings of the following currently-supported properties: `name` and `resourceGroup`<br><br>For example, to get all resources with 'demo' anywhere in the resource name, use `$filter=substringof('demo', name)`<br><br>Multiple substring operations can also be combined using `and`/`or` operators.<br><br>Note that any truncated number of results queried via `$top` may also not be compatible when using a filter.<br><br><br>Resources can be filtered by tag names and values. For example, to filter for a tag name and value, use `$filter=tagName eq 'tag1' and tagValue eq 'Value1'`. Note that when resources are filtered by tag name and value, <b>the original tags for each resource will not be returned in the results.</b> Any list of additional properties queried via `$expand` may also not be compatible when filtering by tag names/values. <br><br>For tag names only, resources can be filtered by prefix using the following syntax: `$filter=startswith(tagName, 'depart')`. This query will return all resources with a tag name prefixed by the phrase `depart` (i.e.`department`, `departureDate`, `departureTime`, etc.)<br><br><br>Note that some properties can be combined when filtering resources, which include the following: `substringof() and/or resourceType`, `plan and plan/publisher and plan/name`, and `identity and identity/principalId`. - /// Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. For example, `$expand=createdTime,changedTime`. - /// The number of recommendations per page if a paged version of this API is being used. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListNextPage(string nextLink, string subscriptionId, string filter = null, string expand = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId, filter, expand, top); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - ResourceListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = ResourceListResult.DeserializeResourceListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/SubscriptionsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/SubscriptionsRestOperations.cs deleted file mode 100644 index a5f94cca14..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/SubscriptionsRestOperations.cs +++ /dev/null @@ -1,341 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class SubscriptionsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of SubscriptionsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public SubscriptionsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2022-12-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateListLocationsRequestUri(string subscriptionId, bool? includeExtendedLocations) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/locations", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (includeExtendedLocations != null) - { - uri.AppendQuery("includeExtendedLocations", includeExtendedLocations.Value, true); - } - return uri; - } - - internal HttpMessage CreateListLocationsRequest(string subscriptionId, bool? includeExtendedLocations) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/locations", false); - uri.AppendQuery("api-version", _apiVersion, true); - if (includeExtendedLocations != null) - { - uri.AppendQuery("includeExtendedLocations", includeExtendedLocations.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation provides all the locations that are available for resource providers; however, each resource provider may support a subset of this list. - /// The ID of the target subscription. - /// Whether to include extended locations. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListLocationsAsync(string subscriptionId, bool? includeExtendedLocations = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListLocationsRequest(subscriptionId, includeExtendedLocations); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - LocationListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = LocationListResult.DeserializeLocationListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation provides all the locations that are available for resource providers; however, each resource provider may support a subset of this list. - /// The ID of the target subscription. - /// Whether to include extended locations. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response ListLocations(string subscriptionId, bool? includeExtendedLocations = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListLocationsRequest(subscriptionId, includeExtendedLocations); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - LocationListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = LocationListResult.DeserializeLocationListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetRequestUri(string subscriptionId) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetRequest(string subscriptionId) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets details about a specified subscription. - /// The ID of the target subscription. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> GetAsync(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateGetRequest(subscriptionId); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - SubscriptionData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = SubscriptionData.DeserializeSubscriptionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((SubscriptionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets details about a specified subscription. - /// The ID of the target subscription. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response Get(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateGetRequest(subscriptionId); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - SubscriptionData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = SubscriptionData.DeserializeSubscriptionData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((SubscriptionData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri() - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListRequest() - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all subscriptions for a tenant. - /// The cancellation token to use. - public async Task> ListAsync(CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - SubscriptionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = SubscriptionListResult.DeserializeSubscriptionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all subscriptions for a tenant. - /// The cancellation token to use. - public Response List(CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - SubscriptionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = SubscriptionListResult.DeserializeSubscriptionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets all subscriptions for a tenant. - /// The URL to the next page of results. - /// The cancellation token to use. - /// is null. - public async Task> ListNextPageAsync(string nextLink, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - SubscriptionListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = SubscriptionListResult.DeserializeSubscriptionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets all subscriptions for a tenant. - /// The URL to the next page of results. - /// The cancellation token to use. - /// is null. - public Response ListNextPage(string nextLink, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - SubscriptionListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = SubscriptionListResult.DeserializeSubscriptionListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/TagsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/TagsRestOperations.cs deleted file mode 100644 index ac7c58fb5a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/TagsRestOperations.cs +++ /dev/null @@ -1,833 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class TagsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of TagsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public TagsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2022-09-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateDeleteValueRequestUri(string subscriptionId, string tagName, string tagValue) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames/", false); - uri.AppendPath(tagName, true); - uri.AppendPath("/tagValues/", false); - uri.AppendPath(tagValue, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteValueRequest(string subscriptionId, string tagName, string tagValue) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames/", false); - uri.AppendPath(tagName, true); - uri.AppendPath("/tagValues/", false); - uri.AppendPath(tagValue, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation allows deleting a value from the list of predefined values for an existing predefined tag name. The value being deleted must not be in use as a tag value for the given tag name for any resource. - /// The ID of the target subscription. - /// The name of the tag. - /// The value of the tag to delete. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public async Task DeleteValueAsync(string subscriptionId, string tagName, string tagValue, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - Argument.AssertNotNullOrEmpty(tagValue, nameof(tagValue)); - - using var message = CreateDeleteValueRequest(subscriptionId, tagName, tagValue); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation allows deleting a value from the list of predefined values for an existing predefined tag name. The value being deleted must not be in use as a tag value for the given tag name for any resource. - /// The ID of the target subscription. - /// The name of the tag. - /// The value of the tag to delete. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public Response DeleteValue(string subscriptionId, string tagName, string tagValue, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - Argument.AssertNotNullOrEmpty(tagValue, nameof(tagValue)); - - using var message = CreateDeleteValueRequest(subscriptionId, tagName, tagValue); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateCreateOrUpdateValueRequestUri(string subscriptionId, string tagName, string tagValue) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames/", false); - uri.AppendPath(tagName, true); - uri.AppendPath("/tagValues/", false); - uri.AppendPath(tagValue, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateValueRequest(string subscriptionId, string tagName, string tagValue) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames/", false); - uri.AppendPath(tagName, true); - uri.AppendPath("/tagValues/", false); - uri.AppendPath(tagValue, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation allows adding a value to the list of predefined values for an existing predefined tag name. A tag value can have a maximum of 256 characters. - /// The ID of the target subscription. - /// The name of the tag. - /// The value of the tag to create. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public async Task> CreateOrUpdateValueAsync(string subscriptionId, string tagName, string tagValue, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - Argument.AssertNotNullOrEmpty(tagValue, nameof(tagValue)); - - using var message = CreateCreateOrUpdateValueRequest(subscriptionId, tagName, tagValue); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 201: - { - PredefinedTagValue value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PredefinedTagValue.DeserializePredefinedTagValue(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation allows adding a value to the list of predefined values for an existing predefined tag name. A tag value can have a maximum of 256 characters. - /// The ID of the target subscription. - /// The name of the tag. - /// The value of the tag to create. - /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public Response CreateOrUpdateValue(string subscriptionId, string tagName, string tagValue, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - Argument.AssertNotNullOrEmpty(tagValue, nameof(tagValue)); - - using var message = CreateCreateOrUpdateValueRequest(subscriptionId, tagName, tagValue); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 201: - { - PredefinedTagValue value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PredefinedTagValue.DeserializePredefinedTagValue(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateCreateOrUpdateRequestUri(string subscriptionId, string tagName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames/", false); - uri.AppendPath(tagName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string tagName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames/", false); - uri.AppendPath(tagName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation allows adding a name to the list of predefined tag names for the given subscription. A tag name can have a maximum of 512 characters and is case-insensitive. Tag names cannot have the following prefixes which are reserved for Azure use: 'microsoft', 'azure', 'windows'. - /// The ID of the target subscription. - /// The name of the tag to create. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task> CreateOrUpdateAsync(string subscriptionId, string tagName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - - using var message = CreateCreateOrUpdateRequest(subscriptionId, tagName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 201: - { - PredefinedTag value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PredefinedTag.DeserializePredefinedTag(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation allows adding a name to the list of predefined tag names for the given subscription. A tag name can have a maximum of 512 characters and is case-insensitive. Tag names cannot have the following prefixes which are reserved for Azure use: 'microsoft', 'azure', 'windows'. - /// The ID of the target subscription. - /// The name of the tag to create. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response CreateOrUpdate(string subscriptionId, string tagName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - - using var message = CreateCreateOrUpdateRequest(subscriptionId, tagName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 201: - { - PredefinedTag value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PredefinedTag.DeserializePredefinedTag(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteRequestUri(string subscriptionId, string tagName) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames/", false); - uri.AppendPath(tagName, true); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteRequest(string subscriptionId, string tagName) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames/", false); - uri.AppendPath(tagName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation allows deleting a name from the list of predefined tag names for the given subscription. The name being deleted must not be in use as a tag name for any resource. All predefined values for the given name must have already been deleted. - /// The ID of the target subscription. - /// The name of the tag. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public async Task DeleteAsync(string subscriptionId, string tagName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - - using var message = CreateDeleteRequest(subscriptionId, tagName); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation allows deleting a name from the list of predefined tag names for the given subscription. The name being deleted must not be in use as a tag name for any resource. All predefined values for the given name must have already been deleted. - /// The ID of the target subscription. - /// The name of the tag. - /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public Response Delete(string subscriptionId, string tagName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - - using var message = CreateDeleteRequest(subscriptionId, tagName); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 204: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListRequestUri(string subscriptionId) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListRequest(string subscriptionId) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/subscriptions/", false); - uri.AppendPath(subscriptionId, true); - uri.AppendPath("/tagNames", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation performs a union of predefined tags, resource tags, resource group tags and subscription tags, and returns a summary of usage for each tag name and value under the given subscription. In case of a large number of tags, this operation may return a previously cached result. - /// The ID of the target subscription. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListAsync(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PredefinedTagsListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PredefinedTagsListResult.DeserializePredefinedTagsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation performs a union of predefined tags, resource tags, resource group tags and subscription tags, and returns a summary of usage for each tag name and value under the given subscription. In case of a large number of tags, this operation may return a previously cached result. - /// The ID of the target subscription. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public Response List(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListRequest(subscriptionId); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PredefinedTagsListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PredefinedTagsListResult.DeserializePredefinedTagsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateCreateOrUpdateAtScopeRequestUri(string scope, TagResourceData data) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Resources/tags/default", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateCreateOrUpdateAtScopeRequest(string scope, TagResourceData data) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Put; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Resources/tags/default", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// This operation allows adding or replacing the entire set of tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags. - /// The resource scope. - /// The to use. - /// The cancellation token to use. - /// or is null. - public async Task CreateOrUpdateAtScopeAsync(string scope, TagResourceData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateAtScopeRequest(scope, data); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation allows adding or replacing the entire set of tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags. - /// The resource scope. - /// The to use. - /// The cancellation token to use. - /// or is null. - public Response CreateOrUpdateAtScope(string scope, TagResourceData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNull(data, nameof(data)); - - using var message = CreateCreateOrUpdateAtScopeRequest(scope, data); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateUpdateAtScopeRequestUri(string scope, TagResourcePatch patch) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Resources/tags/default", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateUpdateAtScopeRequest(string scope, TagResourcePatch patch) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Patch; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Resources/tags/default", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(patch, ModelSerializationExtensions.WireOptions); - request.Content = content; - _userAgent.Apply(message); - return message; - } - - /// This operation allows replacing, merging or selectively deleting tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags at the end of the operation. The 'replace' option replaces the entire set of existing tags with a new set. The 'merge' option allows adding tags with new names and updating the values of tags with existing names. The 'delete' option allows selectively deleting tags based on given names or name/value pairs. - /// The resource scope. - /// The to use. - /// The cancellation token to use. - /// or is null. - public async Task UpdateAtScopeAsync(string scope, TagResourcePatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNull(patch, nameof(patch)); - - using var message = CreateUpdateAtScopeRequest(scope, patch); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation allows replacing, merging or selectively deleting tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags at the end of the operation. The 'replace' option replaces the entire set of existing tags with a new set. The 'merge' option allows adding tags with new names and updating the values of tags with existing names. The 'delete' option allows selectively deleting tags based on given names or name/value pairs. - /// The resource scope. - /// The to use. - /// The cancellation token to use. - /// or is null. - public Response UpdateAtScope(string scope, TagResourcePatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - Argument.AssertNotNull(patch, nameof(patch)); - - using var message = CreateUpdateAtScopeRequest(scope, patch); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetAtScopeRequestUri(string scope) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Resources/tags/default", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateGetAtScopeRequest(string scope) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Resources/tags/default", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets the entire set of tags on a resource or subscription. - /// The resource scope. - /// The cancellation token to use. - /// is null. - public async Task> GetAtScopeAsync(string scope, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - - using var message = CreateGetAtScopeRequest(scope); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - TagResourceData value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = TagResourceData.DeserializeTagResourceData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((TagResourceData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets the entire set of tags on a resource or subscription. - /// The resource scope. - /// The cancellation token to use. - /// is null. - public Response GetAtScope(string scope, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - - using var message = CreateGetAtScopeRequest(scope); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - TagResourceData value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = TagResourceData.DeserializeTagResourceData(document.RootElement); - return Response.FromValue(value, message.Response); - } - case 404: - return Response.FromValue((TagResourceData)null, message.Response); - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateDeleteAtScopeRequestUri(string scope) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Resources/tags/default", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateDeleteAtScopeRequest(string scope) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Delete; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendPath(scope, false); - uri.AppendPath("/providers/Microsoft.Resources/tags/default", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Deletes the entire set of tags on a resource or subscription. - /// The resource scope. - /// The cancellation token to use. - /// is null. - public async Task DeleteAtScopeAsync(string scope, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - - using var message = CreateDeleteAtScopeRequest(scope); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - /// Deletes the entire set of tags on a resource or subscription. - /// The resource scope. - /// The cancellation token to use. - /// is null. - public Response DeleteAtScope(string scope, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(scope, nameof(scope)); - - using var message = CreateDeleteAtScopeRequest(scope); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - case 202: - return message.Response; - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink, string subscriptionId) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// This operation performs a union of predefined tags, resource tags, resource group tags and subscription tags, and returns a summary of usage for each tag name and value under the given subscription. In case of a large number of tags, this operation may return a previously cached result. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public async Task> ListNextPageAsync(string nextLink, string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - PredefinedTagsListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = PredefinedTagsListResult.DeserializePredefinedTagsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// This operation performs a union of predefined tags, resource tags, resource group tags and subscription tags, and returns a summary of usage for each tag name and value under the given subscription. In case of a large number of tags, this operation may return a previously cached result. - /// The URL to the next page of results. - /// The ID of the target subscription. - /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public Response ListNextPage(string nextLink, string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var message = CreateListNextPageRequest(nextLink, subscriptionId); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - PredefinedTagsListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = PredefinedTagsListResult.DeserializePredefinedTagsListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/TenantsRestOperations.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/TenantsRestOperations.cs deleted file mode 100644 index 25264b970e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/RestOperations/TenantsRestOperations.cs +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - internal partial class TenantsRestOperations - { - private readonly TelemetryDetails _userAgent; - private readonly HttpPipeline _pipeline; - private readonly Uri _endpoint; - private readonly string _apiVersion; - - /// Initializes a new instance of TenantsRestOperations. - /// The HTTP pipeline for sending and receiving REST requests and responses. - /// The application id to use for user agent. - /// server parameter. - /// Api Version. - /// or is null. - public TenantsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) - { - _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); - _endpoint = endpoint ?? new Uri("https://management.azure.com"); - _apiVersion = apiVersion ?? "2022-12-01"; - _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); - } - - internal RequestUriBuilder CreateListRequestUri() - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/tenants", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal HttpMessage CreateListRequest() - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/tenants", false); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets the tenants for your account. - /// The cancellation token to use. - public async Task> ListAsync(CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - TenantListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = TenantListResult.DeserializeTenantListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets the tenants for your account. - /// The cancellation token to use. - public Response List(CancellationToken cancellationToken = default) - { - using var message = CreateListRequest(); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - TenantListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = TenantListResult.DeserializeTenantListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - internal RequestUriBuilder CreateGetRequestUri() - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendPath("/", false); - uri.AppendQuery("api-version", _apiVersion, true); - return uri; - } - - internal RequestUriBuilder CreateListNextPageRequestUri(string nextLink) - { - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - return uri; - } - - internal HttpMessage CreateListNextPageRequest(string nextLink) - { - var message = _pipeline.CreateMessage(); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRawNextLink(nextLink, false); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - _userAgent.Apply(message); - return message; - } - - /// Gets the tenants for your account. - /// The URL to the next page of results. - /// The cancellation token to use. - /// is null. - public async Task> ListNextPageAsync(string nextLink, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - switch (message.Response.Status) - { - case 200: - { - TenantListResult value = default; - using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - value = TenantListResult.DeserializeTenantListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - - /// Gets the tenants for your account. - /// The URL to the next page of results. - /// The cancellation token to use. - /// is null. - public Response ListNextPage(string nextLink, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(nextLink, nameof(nextLink)); - - using var message = CreateListNextPageRequest(nextLink); - _pipeline.Send(message, cancellationToken); - switch (message.Response.Status) - { - case 200: - { - TenantListResult value = default; - using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - value = TenantListResult.DeserializeTenantListResult(document.RootElement); - return Response.FromValue(value, message.Response); - } - default: - throw new RequestFailedException(message.Response); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionCollection.cs deleted file mode 100644 index 8ff124397b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionCollection.cs +++ /dev/null @@ -1,394 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetSubscriptions method from an instance of . - /// - public partial class SubscriptionCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _subscriptionClientDiagnostics; - private readonly SubscriptionsRestOperations _subscriptionRestClient; - - /// Initializes a new instance of the class for mocking. - protected SubscriptionCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal SubscriptionCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _subscriptionClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", SubscriptionResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(SubscriptionResource.ResourceType, out string subscriptionApiVersion); - _subscriptionRestClient = new SubscriptionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, subscriptionApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != TenantResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, TenantResource.ResourceType), nameof(id)); - } - - /// - /// Gets details about a specified subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The ID of the target subscription. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _subscriptionClientDiagnostics.CreateScope("SubscriptionCollection.Get"); - scope.Start(); - try - { - var response = await _subscriptionRestClient.GetAsync(subscriptionId, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets details about a specified subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The ID of the target subscription. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _subscriptionClientDiagnostics.CreateScope("SubscriptionCollection.Get"); - scope.Start(); - try - { - var response = _subscriptionRestClient.Get(subscriptionId, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets all subscriptions for a tenant. - /// - /// - /// Request Path - /// /subscriptions - /// - /// - /// Operation Id - /// Subscriptions_List - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionRestClient.CreateListRequest(); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _subscriptionRestClient.CreateListNextPageRequest(nextLink); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new SubscriptionResource(Client, SubscriptionData.DeserializeSubscriptionData(e)), _subscriptionClientDiagnostics, Pipeline, "SubscriptionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Gets all subscriptions for a tenant. - /// - /// - /// Request Path - /// /subscriptions - /// - /// - /// Operation Id - /// Subscriptions_List - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionRestClient.CreateListRequest(); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _subscriptionRestClient.CreateListNextPageRequest(nextLink); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new SubscriptionResource(Client, SubscriptionData.DeserializeSubscriptionData(e)), _subscriptionClientDiagnostics, Pipeline, "SubscriptionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The ID of the target subscription. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _subscriptionClientDiagnostics.CreateScope("SubscriptionCollection.Exists"); - scope.Start(); - try - { - var response = await _subscriptionRestClient.GetAsync(subscriptionId, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The ID of the target subscription. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _subscriptionClientDiagnostics.CreateScope("SubscriptionCollection.Exists"); - scope.Start(); - try - { - var response = _subscriptionRestClient.Get(subscriptionId, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The ID of the target subscription. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _subscriptionClientDiagnostics.CreateScope("SubscriptionCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _subscriptionRestClient.GetAsync(subscriptionId, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new SubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The ID of the target subscription. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string subscriptionId, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); - - using var scope = _subscriptionClientDiagnostics.CreateScope("SubscriptionCollection.GetIfExists"); - scope.Start(); - try - { - var response = _subscriptionRestClient.Get(subscriptionId, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new SubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionData.Serialization.cs deleted file mode 100644 index 44b32c32c3..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionData.Serialization.cs +++ /dev/null @@ -1,481 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class SubscriptionData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SubscriptionData)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && Optional.IsDefined(SubscriptionId)) - { - writer.WritePropertyName("subscriptionId"u8); - writer.WriteStringValue(SubscriptionId); - } - if (options.Format != "W" && Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (options.Format != "W" && Optional.IsDefined(TenantId)) - { - writer.WritePropertyName("tenantId"u8); - writer.WriteStringValue(TenantId.Value); - } - if (options.Format != "W" && Optional.IsDefined(State)) - { - writer.WritePropertyName("state"u8); - writer.WriteStringValue(State.Value.ToSerialString()); - } - if (Optional.IsDefined(SubscriptionPolicies)) - { - writer.WritePropertyName("subscriptionPolicies"u8); - writer.WriteObjectValue(SubscriptionPolicies, options); - } - if (Optional.IsDefined(AuthorizationSource)) - { - writer.WritePropertyName("authorizationSource"u8); - writer.WriteStringValue(AuthorizationSource); - } - if (Optional.IsCollectionDefined(ManagedByTenants)) - { - writer.WritePropertyName("managedByTenants"u8); - writer.WriteStartArray(); - foreach (var item in ManagedByTenants) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(Tags)) - { - writer.WritePropertyName("tags"u8); - writer.WriteStartObject(); - foreach (var item in Tags) - { - writer.WritePropertyName(item.Key); - writer.WriteStringValue(item.Value); - } - writer.WriteEndObject(); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - SubscriptionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(SubscriptionData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeSubscriptionData(document.RootElement, options); - } - - internal static SubscriptionData DeserializeSubscriptionData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ResourceIdentifier id = default; - string subscriptionId = default; - string displayName = default; - Guid? tenantId = default; - SubscriptionState? state = default; - SubscriptionPolicies subscriptionPolicies = default; - string authorizationSource = default; - IReadOnlyList managedByTenants = default; - IReadOnlyDictionary tags = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("subscriptionId"u8)) - { - subscriptionId = property.Value.GetString(); - continue; - } - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (property.NameEquals("tenantId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - tenantId = property.Value.GetGuid(); - continue; - } - if (property.NameEquals("state"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - state = property.Value.GetString().ToSubscriptionState(); - continue; - } - if (property.NameEquals("subscriptionPolicies"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - subscriptionPolicies = SubscriptionPolicies.DeserializeSubscriptionPolicies(property.Value, options); - continue; - } - if (property.NameEquals("authorizationSource"u8)) - { - authorizationSource = property.Value.GetString(); - continue; - } - if (property.NameEquals("managedByTenants"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ManagedByTenant.DeserializeManagedByTenant(item, options)); - } - managedByTenants = array; - continue; - } - if (property.NameEquals("tags"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - tags = dictionary; - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new SubscriptionData( - id, - subscriptionId, - displayName, - tenantId, - state, - subscriptionPolicies, - authorizationSource, - managedByTenants ?? new ChangeTrackingList(), - tags ?? new ChangeTrackingDictionary(), - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SubscriptionId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" subscriptionId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SubscriptionId)) - { - builder.Append(" subscriptionId: "); - if (SubscriptionId.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{SubscriptionId}'''"); - } - else - { - builder.AppendLine($"'{SubscriptionId}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TenantId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenantId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TenantId)) - { - builder.Append(" tenantId: "); - builder.AppendLine($"'{TenantId.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(State), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" state: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(State)) - { - builder.Append(" state: "); - builder.AppendLine($"'{State.Value.ToSerialString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SubscriptionPolicies), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" subscriptionPolicies: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SubscriptionPolicies)) - { - builder.Append(" subscriptionPolicies: "); - BicepSerializationHelpers.AppendChildObject(builder, SubscriptionPolicies, options, 2, false, " subscriptionPolicies: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(AuthorizationSource), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" authorizationSource: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(AuthorizationSource)) - { - builder.Append(" authorizationSource: "); - if (AuthorizationSource.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{AuthorizationSource}'''"); - } - else - { - builder.AppendLine($"'{AuthorizationSource}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(ManagedByTenants), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" managedByTenants: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(ManagedByTenants)) - { - if (ManagedByTenants.Any()) - { - builder.Append(" managedByTenants: "); - builder.AppendLine("["); - foreach (var item in ManagedByTenants) - { - BicepSerializationHelpers.AppendChildObject(builder, item, options, 4, true, " managedByTenants: "); - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Tags), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tags: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Tags)) - { - if (Tags.Any()) - { - builder.Append(" tags: "); - builder.AppendLine("{"); - foreach (var item in Tags) - { - builder.Append($" '{item.Key}': "); - if (item.Value == null) - { - builder.Append("null"); - continue; - } - if (item.Value.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{item.Value}'''"); - } - else - { - builder.AppendLine($"'{item.Value}'"); - } - } - builder.AppendLine(" }"); - } - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(SubscriptionData)} does not support writing '{options.Format}' format."); - } - } - - SubscriptionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeSubscriptionData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(SubscriptionData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionData.cs deleted file mode 100644 index 02537ef7b6..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionData.cs +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the Subscription data model. - /// Subscription information. - /// - public partial class SubscriptionData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal SubscriptionData() - { - ManagedByTenants = new ChangeTrackingList(); - Tags = new ChangeTrackingDictionary(); - } - - /// Initializes a new instance of . - /// The fully qualified ID for the subscription. For example, /subscriptions/8d65815f-a5b6-402f-9298-045155da7d74. - /// The subscription ID. - /// The subscription display name. - /// The subscription tenant ID. - /// The subscription state. Possible values are Enabled, Warned, PastDue, Disabled, and Deleted. - /// The subscription policies. - /// The authorization source of the request. Valid values are one or more combinations of Legacy, RoleBased, Bypassed, Direct and Management. For example, 'Legacy, RoleBased'. - /// An array containing the tenants managing the subscription. - /// The tags attached to the subscription. - /// Keeps track of any properties unknown to the library. - internal SubscriptionData(ResourceIdentifier id, string subscriptionId, string displayName, Guid? tenantId, SubscriptionState? state, SubscriptionPolicies subscriptionPolicies, string authorizationSource, IReadOnlyList managedByTenants, IReadOnlyDictionary tags, IDictionary serializedAdditionalRawData) - { - Id = id; - SubscriptionId = subscriptionId; - DisplayName = displayName; - TenantId = tenantId; - State = state; - SubscriptionPolicies = subscriptionPolicies; - AuthorizationSource = authorizationSource; - ManagedByTenants = managedByTenants; - Tags = tags; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - /// The subscription ID. - [WirePath("subscriptionId")] - public string SubscriptionId { get; } - /// The subscription display name. - [WirePath("displayName")] - public string DisplayName { get; } - /// The subscription tenant ID. - [WirePath("tenantId")] - public Guid? TenantId { get; } - /// The subscription state. Possible values are Enabled, Warned, PastDue, Disabled, and Deleted. - [WirePath("state")] - public SubscriptionState? State { get; } - /// The subscription policies. - [WirePath("subscriptionPolicies")] - public SubscriptionPolicies SubscriptionPolicies { get; } - /// The authorization source of the request. Valid values are one or more combinations of Legacy, RoleBased, Bypassed, Direct and Management. For example, 'Legacy, RoleBased'. - [WirePath("authorizationSource")] - public string AuthorizationSource { get; } - /// An array containing the tenants managing the subscription. - [WirePath("managedByTenants")] - public IReadOnlyList ManagedByTenants { get; } - /// The tags attached to the subscription. - [WirePath("tags")] - public IReadOnlyDictionary Tags { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionCollection.cs deleted file mode 100644 index e0e348db73..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionCollection.cs +++ /dev/null @@ -1,500 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetSubscriptionPolicyDefinitions method from an instance of . - /// - public partial class SubscriptionPolicyDefinitionCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics; - private readonly PolicyDefinitionsRestOperations _subscriptionPolicyDefinitionPolicyDefinitionsRestClient; - - /// Initializes a new instance of the class for mocking. - protected SubscriptionPolicyDefinitionCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal SubscriptionPolicyDefinitionCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", SubscriptionPolicyDefinitionResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(SubscriptionPolicyDefinitionResource.ResourceType, out string subscriptionPolicyDefinitionPolicyDefinitionsApiVersion); - _subscriptionPolicyDefinitionPolicyDefinitionsRestClient = new PolicyDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, subscriptionPolicyDefinitionPolicyDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != SubscriptionResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, SubscriptionResource.ResourceType), nameof(id)); - } - - /// - /// This operation creates or updates a policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy definition to create. - /// The policy definition properties. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string policyDefinitionName, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateOrUpdateAsync(Id.SubscriptionId, policyDefinitionName, data, cancellationToken).ConfigureAwait(false); - var uri = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, policyDefinitionName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy definition to create. - /// The policy definition properties. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string policyDefinitionName, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateOrUpdate(Id.SubscriptionId, policyDefinitionName, data, cancellationToken); - var uri = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, policyDefinitionName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionCollection.Get"); - scope.Start(); - try - { - var response = await _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.GetAsync(Id.SubscriptionId, policyDefinitionName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionCollection.Get"); - scope.Start(); - try - { - var response = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.Get(Id.SubscriptionId, policyDefinitionName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a list of all the policy definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions - /// - /// - /// Operation Id - /// PolicyDefinitions_List - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateListRequest(Id.SubscriptionId, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new SubscriptionPolicyDefinitionResource(Client, PolicyDefinitionData.DeserializePolicyDefinitionData(e)), _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics, Pipeline, "SubscriptionPolicyDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// This operation retrieves a list of all the policy definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions - /// - /// - /// Operation Id - /// PolicyDefinitions_List - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateListRequest(Id.SubscriptionId, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new SubscriptionPolicyDefinitionResource(Client, PolicyDefinitionData.DeserializePolicyDefinitionData(e)), _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics, Pipeline, "SubscriptionPolicyDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = await _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.GetAsync(Id.SubscriptionId, policyDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.Get(Id.SubscriptionId, policyDefinitionName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.GetAsync(Id.SubscriptionId, policyDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.Get(Id.SubscriptionId, policyDefinitionName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionResource.Serialization.cs deleted file mode 100644 index d98f9066c1..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class SubscriptionPolicyDefinitionResource : IJsonModel - { - private static PolicyDefinitionData s_dataDeserializationInstance; - private static PolicyDefinitionData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - PolicyDefinitionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - PolicyDefinitionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionResource.cs deleted file mode 100644 index 415bda5437..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionResource.cs +++ /dev/null @@ -1,353 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a SubscriptionPolicyDefinition along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetSubscriptionPolicyDefinitionResource method. - /// Otherwise you can get one from its parent resource using the GetSubscriptionPolicyDefinition method. - /// - public partial class SubscriptionPolicyDefinitionResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The subscriptionId. - /// The policyDefinitionName. - public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string policyDefinitionName) - { - var resourceId = $"/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics; - private readonly PolicyDefinitionsRestOperations _subscriptionPolicyDefinitionPolicyDefinitionsRestClient; - private readonly PolicyDefinitionData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Authorization/policyDefinitions"; - - /// Initializes a new instance of the class for mocking. - protected SubscriptionPolicyDefinitionResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal SubscriptionPolicyDefinitionResource(ArmClient client, PolicyDefinitionData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal SubscriptionPolicyDefinitionResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string subscriptionPolicyDefinitionPolicyDefinitionsApiVersion); - _subscriptionPolicyDefinitionPolicyDefinitionsRestClient = new PolicyDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, subscriptionPolicyDefinitionPolicyDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual PolicyDefinitionData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionResource.Get"); - scope.Start(); - try - { - var response = await _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.GetAsync(Id.SubscriptionId, Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionResource.Get"); - scope.Start(); - try - { - var response = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.Get(Id.SubscriptionId, Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes the policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Delete - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual async Task DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionResource.Delete"); - scope.Start(); - try - { - var response = await _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.DeleteAsync(Id.SubscriptionId, Id.Name, cancellationToken).ConfigureAwait(false); - var uri = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateDeleteRequestUri(Id.SubscriptionId, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes the policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Delete - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionResource.Delete"); - scope.Start(); - try - { - var response = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.Delete(Id.SubscriptionId, Id.Name, cancellationToken); - var uri = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateDeleteRequestUri(Id.SubscriptionId, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The policy definition properties. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(WaitUntil waitUntil, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionResource.Update"); - scope.Start(); - try - { - var response = await _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.Name, data, cancellationToken).ConfigureAwait(false); - var uri = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The policy definition properties. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation Update(WaitUntil waitUntil, PolicyDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _subscriptionPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicyDefinitionResource.Update"); - scope.Start(); - try - { - var response = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateOrUpdate(Id.SubscriptionId, Id.Name, data, cancellationToken); - var uri = _subscriptionPolicyDefinitionPolicyDefinitionsRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new SubscriptionPolicyDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionCollection.cs deleted file mode 100644 index 3f7c59a96f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionCollection.cs +++ /dev/null @@ -1,500 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetSubscriptionPolicySetDefinitions method from an instance of . - /// - public partial class SubscriptionPolicySetDefinitionCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics; - private readonly PolicySetDefinitionsRestOperations _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient; - - /// Initializes a new instance of the class for mocking. - protected SubscriptionPolicySetDefinitionCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal SubscriptionPolicySetDefinitionCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", SubscriptionPolicySetDefinitionResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(SubscriptionPolicySetDefinitionResource.ResourceType, out string subscriptionPolicySetDefinitionPolicySetDefinitionsApiVersion); - _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient = new PolicySetDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, subscriptionPolicySetDefinitionPolicySetDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != SubscriptionResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, SubscriptionResource.ResourceType), nameof(id)); - } - - /// - /// This operation creates or updates a policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy set definition to create. - /// The policy set definition properties. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string policySetDefinitionName, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateOrUpdateAsync(Id.SubscriptionId, policySetDefinitionName, data, cancellationToken).ConfigureAwait(false); - var uri = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, policySetDefinitionName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The name of the policy set definition to create. - /// The policy set definition properties. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// or is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string policySetDefinitionName, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionCollection.CreateOrUpdate"); - scope.Start(); - try - { - var response = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateOrUpdate(Id.SubscriptionId, policySetDefinitionName, data, cancellationToken); - var uri = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, policySetDefinitionName, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionCollection.Get"); - scope.Start(); - try - { - var response = await _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.GetAsync(Id.SubscriptionId, policySetDefinitionName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionCollection.Get"); - scope.Start(); - try - { - var response = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.Get(Id.SubscriptionId, policySetDefinitionName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a list of all the policy set definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions - /// - /// - /// Operation Id - /// PolicySetDefinitions_List - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListRequest(Id.SubscriptionId, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new SubscriptionPolicySetDefinitionResource(Client, PolicySetDefinitionData.DeserializePolicySetDefinitionData(e)), _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics, Pipeline, "SubscriptionPolicySetDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// This operation retrieves a list of all the policy set definitions in a given subscription that match the optional given $filter. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, the unfiltered list includes all policy set definitions associated with the subscription, including those that apply directly or from management groups that contain the given subscription. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given subscription. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn and Custom. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions - /// - /// - /// Operation Id - /// PolicySetDefinitions_List - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListRequest(Id.SubscriptionId, filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new SubscriptionPolicySetDefinitionResource(Client, PolicySetDefinitionData.DeserializePolicySetDefinitionData(e)), _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics, Pipeline, "SubscriptionPolicySetDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = await _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.GetAsync(Id.SubscriptionId, policySetDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.Get(Id.SubscriptionId, policySetDefinitionName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.GetAsync(Id.SubscriptionId, policySetDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.Get(Id.SubscriptionId, policySetDefinitionName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionResource.Serialization.cs deleted file mode 100644 index 2c9efcff84..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class SubscriptionPolicySetDefinitionResource : IJsonModel - { - private static PolicySetDefinitionData s_dataDeserializationInstance; - private static PolicySetDefinitionData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - PolicySetDefinitionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - PolicySetDefinitionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionResource.cs deleted file mode 100644 index 9bf306c256..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionResource.cs +++ /dev/null @@ -1,353 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a SubscriptionPolicySetDefinition along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetSubscriptionPolicySetDefinitionResource method. - /// Otherwise you can get one from its parent resource using the GetSubscriptionPolicySetDefinition method. - /// - public partial class SubscriptionPolicySetDefinitionResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The subscriptionId. - /// The policySetDefinitionName. - public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string policySetDefinitionName) - { - var resourceId = $"/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics; - private readonly PolicySetDefinitionsRestOperations _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient; - private readonly PolicySetDefinitionData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Authorization/policySetDefinitions"; - - /// Initializes a new instance of the class for mocking. - protected SubscriptionPolicySetDefinitionResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal SubscriptionPolicySetDefinitionResource(ArmClient client, PolicySetDefinitionData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal SubscriptionPolicySetDefinitionResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string subscriptionPolicySetDefinitionPolicySetDefinitionsApiVersion); - _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient = new PolicySetDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, subscriptionPolicySetDefinitionPolicySetDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual PolicySetDefinitionData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionResource.Get"); - scope.Start(); - try - { - var response = await _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.GetAsync(Id.SubscriptionId, Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionResource.Get"); - scope.Start(); - try - { - var response = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.Get(Id.SubscriptionId, Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes the policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Delete - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual async Task DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionResource.Delete"); - scope.Start(); - try - { - var response = await _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.DeleteAsync(Id.SubscriptionId, Id.Name, cancellationToken).ConfigureAwait(false); - var uri = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateDeleteRequestUri(Id.SubscriptionId, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation deletes the policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Delete - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionResource.Delete"); - scope.Start(); - try - { - var response = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.Delete(Id.SubscriptionId, Id.Name, cancellationToken); - var uri = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateDeleteRequestUri(Id.SubscriptionId, Id.Name); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(response, rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The policy set definition properties. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(WaitUntil waitUntil, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionResource.Update"); - scope.Start(); - try - { - var response = await _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.Name, data, cancellationToken).ConfigureAwait(false); - var uri = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation creates or updates a policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The policy set definition properties. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation Update(WaitUntil waitUntil, PolicySetDefinitionData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _subscriptionPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("SubscriptionPolicySetDefinitionResource.Update"); - scope.Start(); - try - { - var response = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateOrUpdate(Id.SubscriptionId, Id.Name, data, cancellationToken); - var uri = _subscriptionPolicySetDefinitionPolicySetDefinitionsRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.Name, data); - var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); - var operation = new ResourcesArmOperation(Response.FromValue(new SubscriptionPolicySetDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionResource.Serialization.cs deleted file mode 100644 index 138601640e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class SubscriptionResource : IJsonModel - { - private static SubscriptionData s_dataDeserializationInstance; - private static SubscriptionData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - SubscriptionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - SubscriptionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionResource.cs deleted file mode 100644 index e484fd200a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/SubscriptionResource.cs +++ /dev/null @@ -1,962 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a Subscription along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetSubscriptionResource method. - /// Otherwise you can get one from its parent resource using the GetSubscription method. - /// - public partial class SubscriptionResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The subscriptionId. - public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId) - { - var resourceId = $"/subscriptions/{subscriptionId}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _subscriptionClientDiagnostics; - private readonly SubscriptionsRestOperations _subscriptionRestClient; - private readonly ClientDiagnostics _subscriptionResourcesClientDiagnostics; - private readonly ResourcesRestOperations _subscriptionResourcesRestClient; - private readonly ClientDiagnostics _subscriptionTagsClientDiagnostics; - private readonly TagsRestOperations _subscriptionTagsRestClient; - private readonly ClientDiagnostics _featureClientDiagnostics; - private readonly FeaturesRestOperations _featureRestClient; - private readonly SubscriptionData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Resources/subscriptions"; - - /// Initializes a new instance of the class for mocking. - protected SubscriptionResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal SubscriptionResource(ArmClient client, SubscriptionData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal SubscriptionResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _subscriptionClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string subscriptionApiVersion); - _subscriptionRestClient = new SubscriptionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, subscriptionApiVersion); - _subscriptionResourcesClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string subscriptionResourcesApiVersion); - _subscriptionResourcesRestClient = new ResourcesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, subscriptionResourcesApiVersion); - _subscriptionTagsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string subscriptionTagsApiVersion); - _subscriptionTagsRestClient = new TagsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, subscriptionTagsApiVersion); - _featureClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", FeatureResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(FeatureResource.ResourceType, out string featureApiVersion); - _featureRestClient = new FeaturesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, featureApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual SubscriptionData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// Gets a collection of SubscriptionPolicyDefinitionResources in the Subscription. - /// An object representing collection of SubscriptionPolicyDefinitionResources and their operations over a SubscriptionPolicyDefinitionResource. - public virtual SubscriptionPolicyDefinitionCollection GetSubscriptionPolicyDefinitions() - { - return GetCachedClient(client => new SubscriptionPolicyDefinitionCollection(client, Id)); - } - - /// - /// This operation retrieves the policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetSubscriptionPolicyDefinitionAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - return await GetSubscriptionPolicyDefinitions().GetAsync(policyDefinitionName, cancellationToken).ConfigureAwait(false); - } - - /// - /// This operation retrieves the policy definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetSubscriptionPolicyDefinition(string policyDefinitionName, CancellationToken cancellationToken = default) - { - return GetSubscriptionPolicyDefinitions().Get(policyDefinitionName, cancellationToken); - } - - /// Gets a collection of SubscriptionPolicySetDefinitionResources in the Subscription. - /// An object representing collection of SubscriptionPolicySetDefinitionResources and their operations over a SubscriptionPolicySetDefinitionResource. - public virtual SubscriptionPolicySetDefinitionCollection GetSubscriptionPolicySetDefinitions() - { - return GetCachedClient(client => new SubscriptionPolicySetDefinitionCollection(client, Id)); - } - - /// - /// This operation retrieves the policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetSubscriptionPolicySetDefinitionAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - return await GetSubscriptionPolicySetDefinitions().GetAsync(policySetDefinitionName, cancellationToken).ConfigureAwait(false); - } - - /// - /// This operation retrieves the policy set definition in the given subscription with the given name. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_Get - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetSubscriptionPolicySetDefinition(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - return GetSubscriptionPolicySetDefinitions().Get(policySetDefinitionName, cancellationToken); - } - - /// Gets a collection of ResourceProviderResources in the Subscription. - /// An object representing collection of ResourceProviderResources and their operations over a ResourceProviderResource. - public virtual ResourceProviderCollection GetResourceProviders() - { - return GetCachedClient(client => new ResourceProviderCollection(client, Id)); - } - - /// - /// Gets the specified resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetResourceProviderAsync(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - return await GetResourceProviders().GetAsync(resourceProviderNamespace, expand, cancellationToken).ConfigureAwait(false); - } - - /// - /// Gets the specified resource provider. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetResourceProvider(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - return GetResourceProviders().Get(resourceProviderNamespace, expand, cancellationToken); - } - - /// Gets a collection of ResourceGroupResources in the Subscription. - /// An object representing collection of ResourceGroupResources and their operations over a ResourceGroupResource. - public virtual ResourceGroupCollection GetResourceGroups() - { - return GetCachedClient(client => new ResourceGroupCollection(client, Id)); - } - - /// - /// Gets a resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetResourceGroupAsync(string resourceGroupName, CancellationToken cancellationToken = default) - { - return await GetResourceGroups().GetAsync(resourceGroupName, cancellationToken).ConfigureAwait(false); - } - - /// - /// Gets a resource group. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName} - /// - /// - /// Operation Id - /// ResourceGroups_Get - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the resource group to get. The name is case insensitive. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetResourceGroup(string resourceGroupName, CancellationToken cancellationToken = default) - { - return GetResourceGroups().Get(resourceGroupName, cancellationToken); - } - - /// - /// Gets details about a specified subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _subscriptionClientDiagnostics.CreateScope("SubscriptionResource.Get"); - scope.Start(); - try - { - var response = await _subscriptionRestClient.GetAsync(Id.SubscriptionId, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets details about a specified subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _subscriptionClientDiagnostics.CreateScope("SubscriptionResource.Get"); - scope.Start(); - try - { - var response = _subscriptionRestClient.Get(Id.SubscriptionId, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new SubscriptionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows deleting a value from the list of predefined values for an existing predefined tag name. The value being deleted must not be in use as a tag value for the given tag name for any resource. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames/{tagName}/tagValues/{tagValue} - /// - /// - /// Operation Id - /// Tags_DeleteValue - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The name of the tag. - /// The value of the tag to delete. - /// The cancellation token to use. - /// or is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task DeletePredefinedTagValueAsync(string tagName, string tagValue, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - Argument.AssertNotNullOrEmpty(tagValue, nameof(tagValue)); - - using var scope = _subscriptionTagsClientDiagnostics.CreateScope("SubscriptionResource.DeletePredefinedTagValue"); - scope.Start(); - try - { - var response = await _subscriptionTagsRestClient.DeleteValueAsync(Id.SubscriptionId, tagName, tagValue, cancellationToken).ConfigureAwait(false); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows deleting a value from the list of predefined values for an existing predefined tag name. The value being deleted must not be in use as a tag value for the given tag name for any resource. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames/{tagName}/tagValues/{tagValue} - /// - /// - /// Operation Id - /// Tags_DeleteValue - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The name of the tag. - /// The value of the tag to delete. - /// The cancellation token to use. - /// or is an empty string, and was expected to be non-empty. - /// or is null. - public virtual Response DeletePredefinedTagValue(string tagName, string tagValue, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - Argument.AssertNotNullOrEmpty(tagValue, nameof(tagValue)); - - using var scope = _subscriptionTagsClientDiagnostics.CreateScope("SubscriptionResource.DeletePredefinedTagValue"); - scope.Start(); - try - { - var response = _subscriptionTagsRestClient.DeleteValue(Id.SubscriptionId, tagName, tagValue, cancellationToken); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows adding a value to the list of predefined values for an existing predefined tag name. A tag value can have a maximum of 256 characters. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames/{tagName}/tagValues/{tagValue} - /// - /// - /// Operation Id - /// Tags_CreateOrUpdateValue - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The name of the tag. - /// The value of the tag to create. - /// The cancellation token to use. - /// or is an empty string, and was expected to be non-empty. - /// or is null. - public virtual async Task> CreateOrUpdatePredefinedTagValueAsync(string tagName, string tagValue, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - Argument.AssertNotNullOrEmpty(tagValue, nameof(tagValue)); - - using var scope = _subscriptionTagsClientDiagnostics.CreateScope("SubscriptionResource.CreateOrUpdatePredefinedTagValue"); - scope.Start(); - try - { - var response = await _subscriptionTagsRestClient.CreateOrUpdateValueAsync(Id.SubscriptionId, tagName, tagValue, cancellationToken).ConfigureAwait(false); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows adding a value to the list of predefined values for an existing predefined tag name. A tag value can have a maximum of 256 characters. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames/{tagName}/tagValues/{tagValue} - /// - /// - /// Operation Id - /// Tags_CreateOrUpdateValue - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The name of the tag. - /// The value of the tag to create. - /// The cancellation token to use. - /// or is an empty string, and was expected to be non-empty. - /// or is null. - public virtual Response CreateOrUpdatePredefinedTagValue(string tagName, string tagValue, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - Argument.AssertNotNullOrEmpty(tagValue, nameof(tagValue)); - - using var scope = _subscriptionTagsClientDiagnostics.CreateScope("SubscriptionResource.CreateOrUpdatePredefinedTagValue"); - scope.Start(); - try - { - var response = _subscriptionTagsRestClient.CreateOrUpdateValue(Id.SubscriptionId, tagName, tagValue, cancellationToken); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows adding a name to the list of predefined tag names for the given subscription. A tag name can have a maximum of 512 characters and is case-insensitive. Tag names cannot have the following prefixes which are reserved for Azure use: 'microsoft', 'azure', 'windows'. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames/{tagName} - /// - /// - /// Operation Id - /// Tags_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The name of the tag to create. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> CreateOrUpdatePredefinedTagAsync(string tagName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - - using var scope = _subscriptionTagsClientDiagnostics.CreateScope("SubscriptionResource.CreateOrUpdatePredefinedTag"); - scope.Start(); - try - { - var response = await _subscriptionTagsRestClient.CreateOrUpdateAsync(Id.SubscriptionId, tagName, cancellationToken).ConfigureAwait(false); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows adding a name to the list of predefined tag names for the given subscription. A tag name can have a maximum of 512 characters and is case-insensitive. Tag names cannot have the following prefixes which are reserved for Azure use: 'microsoft', 'azure', 'windows'. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames/{tagName} - /// - /// - /// Operation Id - /// Tags_CreateOrUpdate - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The name of the tag to create. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response CreateOrUpdatePredefinedTag(string tagName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - - using var scope = _subscriptionTagsClientDiagnostics.CreateScope("SubscriptionResource.CreateOrUpdatePredefinedTag"); - scope.Start(); - try - { - var response = _subscriptionTagsRestClient.CreateOrUpdate(Id.SubscriptionId, tagName, cancellationToken); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows deleting a name from the list of predefined tag names for the given subscription. The name being deleted must not be in use as a tag name for any resource. All predefined values for the given name must have already been deleted. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames/{tagName} - /// - /// - /// Operation Id - /// Tags_Delete - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The name of the tag. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task DeletePredefinedTagAsync(string tagName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - - using var scope = _subscriptionTagsClientDiagnostics.CreateScope("SubscriptionResource.DeletePredefinedTag"); - scope.Start(); - try - { - var response = await _subscriptionTagsRestClient.DeleteAsync(Id.SubscriptionId, tagName, cancellationToken).ConfigureAwait(false); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows deleting a name from the list of predefined tag names for the given subscription. The name being deleted must not be in use as a tag name for any resource. All predefined values for the given name must have already been deleted. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames/{tagName} - /// - /// - /// Operation Id - /// Tags_Delete - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The name of the tag. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response DeletePredefinedTag(string tagName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(tagName, nameof(tagName)); - - using var scope = _subscriptionTagsClientDiagnostics.CreateScope("SubscriptionResource.DeletePredefinedTag"); - scope.Start(); - try - { - var response = _subscriptionTagsRestClient.Delete(Id.SubscriptionId, tagName, cancellationToken); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation performs a union of predefined tags, resource tags, resource group tags and subscription tags, and returns a summary of usage for each tag name and value under the given subscription. In case of a large number of tags, this operation may return a previously cached result. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames - /// - /// - /// Operation Id - /// Tags_List - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllPredefinedTagsAsync(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionTagsRestClient.CreateListRequest(Id.SubscriptionId); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _subscriptionTagsRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => PredefinedTag.DeserializePredefinedTag(e), _subscriptionTagsClientDiagnostics, Pipeline, "SubscriptionResource.GetAllPredefinedTags", "value", "nextLink", cancellationToken); - } - - /// - /// This operation performs a union of predefined tags, resource tags, resource group tags and subscription tags, and returns a summary of usage for each tag name and value under the given subscription. In case of a large number of tags, this operation may return a previously cached result. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/tagNames - /// - /// - /// Operation Id - /// Tags_List - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAllPredefinedTags(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionTagsRestClient.CreateListRequest(Id.SubscriptionId); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _subscriptionTagsRestClient.CreateListNextPageRequest(nextLink, Id.SubscriptionId); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => PredefinedTag.DeserializePredefinedTag(e), _subscriptionTagsClientDiagnostics, Pipeline, "SubscriptionResource.GetAllPredefinedTags", "value", "nextLink", cancellationToken); - } - - /// - /// This operation provides all the locations that are available for resource providers; however, each resource provider may support a subset of this list. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/locations - /// - /// - /// Operation Id - /// Subscriptions_ListLocations - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Whether to include extended locations. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetLocationsAsync(bool? includeExtendedLocations = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionRestClient.CreateListLocationsRequest(Id.SubscriptionId, includeExtendedLocations); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, null, e => LocationExpanded.DeserializeLocationExpanded(e), _subscriptionClientDiagnostics, Pipeline, "SubscriptionResource.GetLocations", "value", null, cancellationToken); - } - - /// - /// This operation provides all the locations that are available for resource providers; however, each resource provider may support a subset of this list. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/locations - /// - /// - /// Operation Id - /// Subscriptions_ListLocations - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// Whether to include extended locations. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetLocations(bool? includeExtendedLocations = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _subscriptionRestClient.CreateListLocationsRequest(Id.SubscriptionId, includeExtendedLocations); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, null, e => LocationExpanded.DeserializeLocationExpanded(e), _subscriptionClientDiagnostics, Pipeline, "SubscriptionResource.GetLocations", "value", null, cancellationToken); - } - - /// - /// Gets all the preview features that are available through AFEC for the subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/features - /// - /// - /// Operation Id - /// Features_ListAll - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetFeaturesAsync(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _featureRestClient.CreateListAllRequest(Id.SubscriptionId); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _featureRestClient.CreateListAllNextPageRequest(nextLink, Id.SubscriptionId); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new FeatureResource(Client, FeatureData.DeserializeFeatureData(e)), _featureClientDiagnostics, Pipeline, "SubscriptionResource.GetFeatures", "value", "nextLink", cancellationToken); - } - - /// - /// Gets all the preview features that are available through AFEC for the subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId}/providers/Microsoft.Features/features - /// - /// - /// Operation Id - /// Features_ListAll - /// - /// - /// Default Api Version - /// 2021-07-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetFeatures(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _featureRestClient.CreateListAllRequest(Id.SubscriptionId); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _featureRestClient.CreateListAllNextPageRequest(nextLink, Id.SubscriptionId); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new FeatureResource(Client, FeatureData.DeserializeFeatureData(e)), _featureClientDiagnostics, Pipeline, "SubscriptionResource.GetFeatures", "value", "nextLink", cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TagResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TagResource.Serialization.cs deleted file mode 100644 index 14b43eb7c4..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TagResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class TagResource : IJsonModel - { - private static TagResourceData s_dataDeserializationInstance; - private static TagResourceData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - TagResourceData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - TagResourceData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TagResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TagResource.cs deleted file mode 100644 index f63e4775de..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TagResource.cs +++ /dev/null @@ -1,437 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a TagResource along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetTagResource method. - /// Otherwise you can get one from its parent resource using the GetTagResource method. - /// - public partial class TagResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The scope. - public static ResourceIdentifier CreateResourceIdentifier(string scope) - { - var resourceId = $"{scope}/providers/Microsoft.Resources/tags/default"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _tagResourceTagsClientDiagnostics; - private readonly TagsRestOperations _tagResourceTagsRestClient; - private readonly TagResourceData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Resources/tags"; - - /// Initializes a new instance of the class for mocking. - protected TagResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal TagResource(ArmClient client, TagResourceData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal TagResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _tagResourceTagsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string tagResourceTagsApiVersion); - _tagResourceTagsRestClient = new TagsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, tagResourceTagsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual TagResourceData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// Gets the entire set of tags on a resource or subscription. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_GetAtScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _tagResourceTagsClientDiagnostics.CreateScope("TagResource.Get"); - scope.Start(); - try - { - var response = await _tagResourceTagsRestClient.GetAtScopeAsync(Id.Parent, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TagResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets the entire set of tags on a resource or subscription. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_GetAtScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _tagResourceTagsClientDiagnostics.CreateScope("TagResource.Get"); - scope.Start(); - try - { - var response = _tagResourceTagsRestClient.GetAtScope(Id.Parent, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TagResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Deletes the entire set of tags on a resource or subscription. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_DeleteAtScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual async Task DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _tagResourceTagsClientDiagnostics.CreateScope("TagResource.Delete"); - scope.Start(); - try - { - var response = await _tagResourceTagsRestClient.DeleteAtScopeAsync(Id.Parent, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(_tagResourceTagsClientDiagnostics, Pipeline, _tagResourceTagsRestClient.CreateDeleteAtScopeRequest(Id.Parent).Request, response, OperationFinalStateVia.Location, skipApiVersionOverride: true); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Deletes the entire set of tags on a resource or subscription. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_DeleteAtScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The cancellation token to use. - public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) - { - using var scope = _tagResourceTagsClientDiagnostics.CreateScope("TagResource.Delete"); - scope.Start(); - try - { - var response = _tagResourceTagsRestClient.DeleteAtScope(Id.Parent, cancellationToken); - var operation = new ResourcesArmOperation(_tagResourceTagsClientDiagnostics, Pipeline, _tagResourceTagsRestClient.CreateDeleteAtScopeRequest(Id.Parent).Request, response, OperationFinalStateVia.Location, skipApiVersionOverride: true); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletionResponse(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows replacing, merging or selectively deleting tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags at the end of the operation. The 'replace' option replaces the entire set of existing tags with a new set. The 'merge' option allows adding tags with new names and updating the values of tags with existing names. The 'delete' option allows selectively deleting tags based on given names or name/value pairs. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_UpdateAtScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The to use. - /// The cancellation token to use. - /// is null. - public virtual async Task> UpdateAsync(WaitUntil waitUntil, TagResourcePatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(patch, nameof(patch)); - - using var scope = _tagResourceTagsClientDiagnostics.CreateScope("TagResource.Update"); - scope.Start(); - try - { - var response = await _tagResourceTagsRestClient.UpdateAtScopeAsync(Id.Parent, patch, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(new TagResourceOperationSource(Client), _tagResourceTagsClientDiagnostics, Pipeline, _tagResourceTagsRestClient.CreateUpdateAtScopeRequest(Id.Parent, patch).Request, response, OperationFinalStateVia.Location, skipApiVersionOverride: true); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows replacing, merging or selectively deleting tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags at the end of the operation. The 'replace' option replaces the entire set of existing tags with a new set. The 'merge' option allows adding tags with new names and updating the values of tags with existing names. The 'delete' option allows selectively deleting tags based on given names or name/value pairs. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_UpdateAtScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The to use. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation Update(WaitUntil waitUntil, TagResourcePatch patch, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(patch, nameof(patch)); - - using var scope = _tagResourceTagsClientDiagnostics.CreateScope("TagResource.Update"); - scope.Start(); - try - { - var response = _tagResourceTagsRestClient.UpdateAtScope(Id.Parent, patch, cancellationToken); - var operation = new ResourcesArmOperation(new TagResourceOperationSource(Client), _tagResourceTagsClientDiagnostics, Pipeline, _tagResourceTagsRestClient.CreateUpdateAtScopeRequest(Id.Parent, patch).Request, response, OperationFinalStateVia.Location, skipApiVersionOverride: true); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows adding or replacing the entire set of tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_CreateOrUpdateAtScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The to use. - /// The cancellation token to use. - /// is null. - public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, TagResourceData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _tagResourceTagsClientDiagnostics.CreateScope("TagResource.CreateOrUpdate"); - scope.Start(); - try - { - var response = await _tagResourceTagsRestClient.CreateOrUpdateAtScopeAsync(Id.Parent, data, cancellationToken).ConfigureAwait(false); - var operation = new ResourcesArmOperation(new TagResourceOperationSource(Client), _tagResourceTagsClientDiagnostics, Pipeline, _tagResourceTagsRestClient.CreateCreateOrUpdateAtScopeRequest(Id.Parent, data).Request, response, OperationFinalStateVia.Location, skipApiVersionOverride: true); - if (waitUntil == WaitUntil.Completed) - await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation allows adding or replacing the entire set of tags on the specified resource or subscription. The specified entity can have a maximum of 50 tags. - /// - /// - /// Request Path - /// /{scope}/providers/Microsoft.Resources/tags/default - /// - /// - /// Operation Id - /// Tags_CreateOrUpdateAtScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - /// The to use. - /// The cancellation token to use. - /// is null. - public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, TagResourceData data, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(data, nameof(data)); - - using var scope = _tagResourceTagsClientDiagnostics.CreateScope("TagResource.CreateOrUpdate"); - scope.Start(); - try - { - var response = _tagResourceTagsRestClient.CreateOrUpdateAtScope(Id.Parent, data, cancellationToken); - var operation = new ResourcesArmOperation(new TagResourceOperationSource(Client), _tagResourceTagsClientDiagnostics, Pipeline, _tagResourceTagsRestClient.CreateCreateOrUpdateAtScopeRequest(Id.Parent, data).Request, response, OperationFinalStateVia.Location, skipApiVersionOverride: true); - if (waitUntil == WaitUntil.Completed) - operation.WaitForCompletion(cancellationToken); - return operation; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TagResourceData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TagResourceData.Serialization.cs deleted file mode 100644 index 29ce35e544..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TagResourceData.Serialization.cs +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class TagResourceData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TagResourceData)} does not support writing '{format}' format."); - } - - base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("properties"u8); - writer.WriteObjectValue(Properties, options); - } - - TagResourceData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TagResourceData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeTagResourceData(document.RootElement, options); - } - - internal static TagResourceData DeserializeTagResourceData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - Tag properties = default; - ResourceIdentifier id = default; - string name = default; - ResourceType type = default; - SystemData systemData = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("properties"u8)) - { - properties = Tag.DeserializeTag(property.Value, options); - continue; - } - if (property.NameEquals("id"u8)) - { - id = new ResourceIdentifier(property.Value.GetString()); - continue; - } - if (property.NameEquals("name"u8)) - { - name = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = new ResourceType(property.Value.GetString()); - continue; - } - if (property.NameEquals("systemData"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - systemData = JsonSerializer.Deserialize(property.Value.GetRawText()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new TagResourceData( - id, - name, - type, - systemData, - properties, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Name), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" name: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Name)) - { - builder.Append(" name: "); - if (Name.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Name}'''"); - } - else - { - builder.AppendLine($"'{Name}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue("TagValues", out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" properties: "); - builder.AppendLine("{"); - builder.Append(" tags: "); - builder.AppendLine(propertyOverride); - builder.AppendLine(" }"); - } - else - { - if (Optional.IsDefined(Properties)) - { - builder.Append(" properties: "); - BicepSerializationHelpers.AppendChildObject(builder, Properties, options, 2, false, " properties: "); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - builder.AppendLine($"'{Id.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(SystemData), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" systemData: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(SystemData)) - { - builder.Append(" systemData: "); - builder.AppendLine($"'{SystemData.ToString()}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(TagResourceData)} does not support writing '{options.Format}' format."); - } - } - - TagResourceData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeTagResourceData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(TagResourceData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TagResourceData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TagResourceData.cs deleted file mode 100644 index 8bda3dfa58..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TagResourceData.cs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.Core; -using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the TagResource data model. - /// Wrapper resource for tags API requests and responses. - /// - public partial class TagResourceData : ResourceData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The set of tags. - /// is null. - public TagResourceData(Tag properties) - { - Argument.AssertNotNull(properties, nameof(properties)); - - Properties = properties; - } - - /// Initializes a new instance of . - /// The id. - /// The name. - /// The resourceType. - /// The systemData. - /// The set of tags. - /// Keeps track of any properties unknown to the library. - internal TagResourceData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, Tag properties, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) - { - Properties = properties; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal TagResourceData() - { - } - - /// The set of tags. - internal Tag Properties { get; set; } - /// Dictionary of <string>. - [WirePath("properties.tags")] - public IDictionary TagValues - { - get - { - if (Properties is null) - Properties = new Tag(); - return Properties.TagValues; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantCollection.cs deleted file mode 100644 index 53cd523d8b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantCollection.cs +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// A class representing a collection of and their operations. - public partial class TenantCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _tenantClientDiagnostics; - private readonly TenantsRestOperations _tenantRestClient; - private readonly ClientDiagnostics _defaultClientDiagnostics; - private readonly ResourceManagementRestOperations _defaultRestClient; - - /// Initializes a new instance of the class for mocking. - protected TenantCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal TenantCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _tenantClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", TenantResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(TenantResource.ResourceType, out string tenantApiVersion); - _tenantRestClient = new TenantsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, tenantApiVersion); - _defaultClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ProviderConstants.DefaultProviderNamespace, Diagnostics); - _defaultRestClient = new ResourceManagementRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != TenantResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, TenantResource.ResourceType), nameof(id)); - } - - /// - /// Gets the tenants for your account. - /// - /// - /// Request Path - /// /tenants - /// - /// - /// Operation Id - /// Tenants_List - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _tenantRestClient.CreateListRequest(); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _tenantRestClient.CreateListNextPageRequest(nextLink); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new TenantResource(Client, TenantData.DeserializeTenantData(e)), _tenantClientDiagnostics, Pipeline, "TenantCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Gets the tenants for your account. - /// - /// - /// Request Path - /// /tenants - /// - /// - /// Operation Id - /// Tenants_List - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _tenantRestClient.CreateListRequest(); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _tenantRestClient.CreateListNextPageRequest(nextLink); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new TenantResource(Client, TenantData.DeserializeTenantData(e)), _tenantClientDiagnostics, Pipeline, "TenantCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// A resource name is valid if it is not a reserved word, does not contains a reserved word and does not start with a reserved word - /// - /// - /// Request Path - /// /providers/Microsoft.Resources/checkResourceName - /// - /// - /// Operation Id - /// CheckResourceName - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// - /// Resource object with values for resource name and resource type. - /// The cancellation token to use. - public virtual async Task> CheckResourceNameAsync(ResourceNameValidationContent content = null, CancellationToken cancellationToken = default) - { - using var scope = _defaultClientDiagnostics.CreateScope("TenantCollection.CheckResourceName"); - scope.Start(); - try - { - var response = await _defaultRestClient.CheckResourceNameAsync(content, cancellationToken).ConfigureAwait(false); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// A resource name is valid if it is not a reserved word, does not contains a reserved word and does not start with a reserved word - /// - /// - /// Request Path - /// /providers/Microsoft.Resources/checkResourceName - /// - /// - /// Operation Id - /// CheckResourceName - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// - /// Resource object with values for resource name and resource type. - /// The cancellation token to use. - public virtual Response CheckResourceName(ResourceNameValidationContent content = null, CancellationToken cancellationToken = default) - { - using var scope = _defaultClientDiagnostics.CreateScope("TenantCollection.CheckResourceName"); - scope.Start(); - try - { - var response = _defaultRestClient.CheckResourceName(content, cancellationToken); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantData.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantData.Serialization.cs deleted file mode 100644 index 4449446703..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantData.Serialization.cs +++ /dev/null @@ -1,504 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using Azure.Core; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - public partial class TenantData : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TenantData)} does not support writing '{format}' format."); - } - - if (options.Format != "W" && Optional.IsDefined(Id)) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && Optional.IsDefined(TenantId)) - { - writer.WritePropertyName("tenantId"u8); - writer.WriteStringValue(TenantId.Value); - } - if (options.Format != "W" && Optional.IsDefined(TenantCategory)) - { - writer.WritePropertyName("tenantCategory"u8); - writer.WriteStringValue(TenantCategory.Value.ToSerialString()); - } - if (options.Format != "W" && Optional.IsDefined(Country)) - { - writer.WritePropertyName("country"u8); - writer.WriteStringValue(Country); - } - if (options.Format != "W" && Optional.IsDefined(CountryCode)) - { - writer.WritePropertyName("countryCode"u8); - writer.WriteStringValue(CountryCode); - } - if (options.Format != "W" && Optional.IsDefined(DisplayName)) - { - writer.WritePropertyName("displayName"u8); - writer.WriteStringValue(DisplayName); - } - if (options.Format != "W" && Optional.IsCollectionDefined(Domains)) - { - writer.WritePropertyName("domains"u8); - writer.WriteStartArray(); - foreach (var item in Domains) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && Optional.IsDefined(DefaultDomain)) - { - writer.WritePropertyName("defaultDomain"u8); - writer.WriteStringValue(DefaultDomain); - } - if (options.Format != "W" && Optional.IsDefined(TenantType)) - { - writer.WritePropertyName("tenantType"u8); - writer.WriteStringValue(TenantType); - } - if (options.Format != "W" && Optional.IsDefined(TenantBrandingLogoUri)) - { - writer.WritePropertyName("tenantBrandingLogoUrl"u8); - writer.WriteStringValue(TenantBrandingLogoUri.AbsoluteUri); - } - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - TenantData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(TenantData)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeTenantData(document.RootElement, options); - } - - internal static TenantData DeserializeTenantData(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string id = default; - Guid? tenantId = default; - TenantCategory? tenantCategory = default; - string country = default; - string countryCode = default; - string displayName = default; - IReadOnlyList domains = default; - string defaultDomain = default; - string tenantType = default; - Uri tenantBrandingLogoUrl = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("tenantId"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - tenantId = property.Value.GetGuid(); - continue; - } - if (property.NameEquals("tenantCategory"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - tenantCategory = property.Value.GetString().ToTenantCategory(); - continue; - } - if (property.NameEquals("country"u8)) - { - country = property.Value.GetString(); - continue; - } - if (property.NameEquals("countryCode"u8)) - { - countryCode = property.Value.GetString(); - continue; - } - if (property.NameEquals("displayName"u8)) - { - displayName = property.Value.GetString(); - continue; - } - if (property.NameEquals("domains"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - domains = array; - continue; - } - if (property.NameEquals("defaultDomain"u8)) - { - defaultDomain = property.Value.GetString(); - continue; - } - if (property.NameEquals("tenantType"u8)) - { - tenantType = property.Value.GetString(); - continue; - } - if (property.NameEquals("tenantBrandingLogoUrl"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - tenantBrandingLogoUrl = new Uri(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new TenantData( - id, - tenantId, - tenantCategory, - country, - countryCode, - displayName, - domains ?? new ChangeTrackingList(), - defaultDomain, - tenantType, - tenantBrandingLogoUrl, - serializedAdditionalRawData); - } - - private BinaryData SerializeBicep(ModelReaderWriterOptions options) - { - StringBuilder builder = new StringBuilder(); - BicepModelReaderWriterOptions bicepOptions = options as BicepModelReaderWriterOptions; - IDictionary propertyOverrides = null; - bool hasObjectOverride = bicepOptions != null && bicepOptions.PropertyOverrides.TryGetValue(this, out propertyOverrides); - bool hasPropertyOverride = false; - string propertyOverride = null; - - builder.AppendLine("{"); - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Id), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" id: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Id)) - { - builder.Append(" id: "); - if (Id.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Id}'''"); - } - else - { - builder.AppendLine($"'{Id}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TenantId), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenantId: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TenantId)) - { - builder.Append(" tenantId: "); - builder.AppendLine($"'{TenantId.Value.ToString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TenantCategory), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenantCategory: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TenantCategory)) - { - builder.Append(" tenantCategory: "); - builder.AppendLine($"'{TenantCategory.Value.ToSerialString()}'"); - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Country), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" country: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(Country)) - { - builder.Append(" country: "); - if (Country.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{Country}'''"); - } - else - { - builder.AppendLine($"'{Country}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(CountryCode), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" countryCode: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(CountryCode)) - { - builder.Append(" countryCode: "); - if (CountryCode.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{CountryCode}'''"); - } - else - { - builder.AppendLine($"'{CountryCode}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DisplayName), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" displayName: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DisplayName)) - { - builder.Append(" displayName: "); - if (DisplayName.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DisplayName}'''"); - } - else - { - builder.AppendLine($"'{DisplayName}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(Domains), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" domains: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsCollectionDefined(Domains)) - { - if (Domains.Any()) - { - builder.Append(" domains: "); - builder.AppendLine("["); - foreach (var item in Domains) - { - if (item == null) - { - builder.Append("null"); - continue; - } - if (item.Contains(Environment.NewLine)) - { - builder.AppendLine(" '''"); - builder.AppendLine($"{item}'''"); - } - else - { - builder.AppendLine($" '{item}'"); - } - } - builder.AppendLine(" ]"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(DefaultDomain), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" defaultDomain: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(DefaultDomain)) - { - builder.Append(" defaultDomain: "); - if (DefaultDomain.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{DefaultDomain}'''"); - } - else - { - builder.AppendLine($"'{DefaultDomain}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TenantType), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenantType: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TenantType)) - { - builder.Append(" tenantType: "); - if (TenantType.Contains(Environment.NewLine)) - { - builder.AppendLine("'''"); - builder.AppendLine($"{TenantType}'''"); - } - else - { - builder.AppendLine($"'{TenantType}'"); - } - } - } - - hasPropertyOverride = hasObjectOverride && propertyOverrides.TryGetValue(nameof(TenantBrandingLogoUri), out propertyOverride); - if (hasPropertyOverride) - { - builder.Append(" tenantBrandingLogoUrl: "); - builder.AppendLine(propertyOverride); - } - else - { - if (Optional.IsDefined(TenantBrandingLogoUri)) - { - builder.Append(" tenantBrandingLogoUrl: "); - builder.AppendLine($"'{TenantBrandingLogoUri.AbsoluteUri}'"); - } - } - - builder.AppendLine("}"); - return BinaryData.FromString(builder.ToString()); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options, AzureResourceManagerContext.Default); - case "bicep": - return SerializeBicep(options); - default: - throw new FormatException($"The model {nameof(TenantData)} does not support writing '{options.Format}' format."); - } - } - - TenantData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeTenantData(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(TenantData)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantData.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantData.cs deleted file mode 100644 index 7d91999217..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantData.cs +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing the Tenant data model. - /// Tenant Id information. - /// - public partial class TenantData - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - internal TenantData() - { - Domains = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The fully qualified ID of the tenant. For example, /tenants/8d65815f-a5b6-402f-9298-045155da7d74. - /// The tenant ID. For example, 8d65815f-a5b6-402f-9298-045155da7d74. - /// Category of the tenant. - /// Country/region name of the address for the tenant. - /// Country/region abbreviation for the tenant. - /// The display name of the tenant. - /// The list of domains for the tenant. - /// The default domain for the tenant. - /// The tenant type. Only available for 'Home' tenant category. - /// The tenant's branding logo URL. Only available for 'Home' tenant category. - /// Keeps track of any properties unknown to the library. - internal TenantData(string id, Guid? tenantId, TenantCategory? tenantCategory, string country, string countryCode, string displayName, IReadOnlyList domains, string defaultDomain, string tenantType, Uri tenantBrandingLogoUri, IDictionary serializedAdditionalRawData) - { - Id = id; - TenantId = tenantId; - TenantCategory = tenantCategory; - Country = country; - CountryCode = countryCode; - DisplayName = displayName; - Domains = domains; - DefaultDomain = defaultDomain; - TenantType = tenantType; - TenantBrandingLogoUri = tenantBrandingLogoUri; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The fully qualified ID of the tenant. For example, /tenants/8d65815f-a5b6-402f-9298-045155da7d74. - [WirePath("id")] - public string Id { get; } - /// The tenant ID. For example, 8d65815f-a5b6-402f-9298-045155da7d74. - [WirePath("tenantId")] - public Guid? TenantId { get; } - /// Category of the tenant. - [WirePath("tenantCategory")] - public TenantCategory? TenantCategory { get; } - /// Country/region name of the address for the tenant. - [WirePath("country")] - public string Country { get; } - /// Country/region abbreviation for the tenant. - [WirePath("countryCode")] - public string CountryCode { get; } - /// The display name of the tenant. - [WirePath("displayName")] - public string DisplayName { get; } - /// The list of domains for the tenant. - [WirePath("domains")] - public IReadOnlyList Domains { get; } - /// The default domain for the tenant. - [WirePath("defaultDomain")] - public string DefaultDomain { get; } - /// The tenant type. Only available for 'Home' tenant category. - [WirePath("tenantType")] - public string TenantType { get; } - /// The tenant's branding logo URL. Only available for 'Home' tenant category. - [WirePath("tenantBrandingLogoUrl")] - public Uri TenantBrandingLogoUri { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionCollection.cs deleted file mode 100644 index bd817fab6a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionCollection.cs +++ /dev/null @@ -1,398 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetTenantPolicyDefinitions method from an instance of . - /// - public partial class TenantPolicyDefinitionCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics; - private readonly PolicyDefinitionsRestOperations _tenantPolicyDefinitionPolicyDefinitionsRestClient; - - /// Initializes a new instance of the class for mocking. - protected TenantPolicyDefinitionCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal TenantPolicyDefinitionCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", TenantPolicyDefinitionResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(TenantPolicyDefinitionResource.ResourceType, out string tenantPolicyDefinitionPolicyDefinitionsApiVersion); - _tenantPolicyDefinitionPolicyDefinitionsRestClient = new PolicyDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, tenantPolicyDefinitionPolicyDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != TenantResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, TenantResource.ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the built-in policy definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("TenantPolicyDefinitionCollection.Get"); - scope.Start(); - try - { - var response = await _tenantPolicyDefinitionPolicyDefinitionsRestClient.GetBuiltInAsync(policyDefinitionName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TenantPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the built-in policy definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("TenantPolicyDefinitionCollection.Get"); - scope.Start(); - try - { - var response = _tenantPolicyDefinitionPolicyDefinitionsRestClient.GetBuiltIn(policyDefinitionName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TenantPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a list of all the built-in policy definitions that match the optional given $filter. If $filter='policyType -eq {value}' is provided, the returned list only includes all built-in policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy definitions whose category match the {value}. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions - /// - /// - /// Operation Id - /// PolicyDefinitions_ListBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _tenantPolicyDefinitionPolicyDefinitionsRestClient.CreateListBuiltInRequest(filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _tenantPolicyDefinitionPolicyDefinitionsRestClient.CreateListBuiltInNextPageRequest(nextLink, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new TenantPolicyDefinitionResource(Client, PolicyDefinitionData.DeserializePolicyDefinitionData(e)), _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics, Pipeline, "TenantPolicyDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// This operation retrieves a list of all the built-in policy definitions that match the optional given $filter. If $filter='policyType -eq {value}' is provided, the returned list only includes all built-in policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy definitions whose category match the {value}. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions - /// - /// - /// Operation Id - /// PolicyDefinitions_ListBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _tenantPolicyDefinitionPolicyDefinitionsRestClient.CreateListBuiltInRequest(filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _tenantPolicyDefinitionPolicyDefinitionsRestClient.CreateListBuiltInNextPageRequest(nextLink, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new TenantPolicyDefinitionResource(Client, PolicyDefinitionData.DeserializePolicyDefinitionData(e)), _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics, Pipeline, "TenantPolicyDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("TenantPolicyDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = await _tenantPolicyDefinitionPolicyDefinitionsRestClient.GetBuiltInAsync(policyDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("TenantPolicyDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = _tenantPolicyDefinitionPolicyDefinitionsRestClient.GetBuiltIn(policyDefinitionName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("TenantPolicyDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _tenantPolicyDefinitionPolicyDefinitionsRestClient.GetBuiltInAsync(policyDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new TenantPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string policyDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policyDefinitionName, nameof(policyDefinitionName)); - - using var scope = _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("TenantPolicyDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = _tenantPolicyDefinitionPolicyDefinitionsRestClient.GetBuiltIn(policyDefinitionName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new TenantPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionResource.Serialization.cs deleted file mode 100644 index 6d08620cc8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class TenantPolicyDefinitionResource : IJsonModel - { - private static PolicyDefinitionData s_dataDeserializationInstance; - private static PolicyDefinitionData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - PolicyDefinitionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - PolicyDefinitionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionResource.cs deleted file mode 100644 index a8464ce670..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionResource.cs +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a TenantPolicyDefinition along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetTenantPolicyDefinitionResource method. - /// Otherwise you can get one from its parent resource using the GetTenantPolicyDefinition method. - /// - public partial class TenantPolicyDefinitionResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The policyDefinitionName. - public static ResourceIdentifier CreateResourceIdentifier(string policyDefinitionName) - { - var resourceId = $"/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics; - private readonly PolicyDefinitionsRestOperations _tenantPolicyDefinitionPolicyDefinitionsRestClient; - private readonly PolicyDefinitionData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Authorization/policyDefinitions"; - - /// Initializes a new instance of the class for mocking. - protected TenantPolicyDefinitionResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal TenantPolicyDefinitionResource(ArmClient client, PolicyDefinitionData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal TenantPolicyDefinitionResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string tenantPolicyDefinitionPolicyDefinitionsApiVersion); - _tenantPolicyDefinitionPolicyDefinitionsRestClient = new PolicyDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, tenantPolicyDefinitionPolicyDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual PolicyDefinitionData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the built-in policy definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("TenantPolicyDefinitionResource.Get"); - scope.Start(); - try - { - var response = await _tenantPolicyDefinitionPolicyDefinitionsRestClient.GetBuiltInAsync(Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TenantPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the built-in policy definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _tenantPolicyDefinitionPolicyDefinitionsClientDiagnostics.CreateScope("TenantPolicyDefinitionResource.Get"); - scope.Start(); - try - { - var response = _tenantPolicyDefinitionPolicyDefinitionsRestClient.GetBuiltIn(Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TenantPolicyDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionCollection.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionCollection.cs deleted file mode 100644 index dbc7feb42d..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionCollection.cs +++ /dev/null @@ -1,398 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A class representing a collection of and their operations. - /// Each in the collection will belong to the same instance of . - /// To get a instance call the GetTenantPolicySetDefinitions method from an instance of . - /// - public partial class TenantPolicySetDefinitionCollection : ArmCollection, IEnumerable, IAsyncEnumerable - { - private readonly ClientDiagnostics _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics; - private readonly PolicySetDefinitionsRestOperations _tenantPolicySetDefinitionPolicySetDefinitionsRestClient; - - /// Initializes a new instance of the class for mocking. - protected TenantPolicySetDefinitionCollection() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the parent resource that is the target of operations. - internal TenantPolicySetDefinitionCollection(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", TenantPolicySetDefinitionResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(TenantPolicySetDefinitionResource.ResourceType, out string tenantPolicySetDefinitionPolicySetDefinitionsApiVersion); - _tenantPolicySetDefinitionPolicySetDefinitionsRestClient = new PolicySetDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, tenantPolicySetDefinitionPolicySetDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != TenantResource.ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, TenantResource.ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the built-in policy set definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.Get"); - scope.Start(); - try - { - var response = await _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltInAsync(policySetDefinitionName, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TenantPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the built-in policy set definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Get(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.Get"); - scope.Start(); - try - { - var response = _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltIn(policySetDefinitionName, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TenantPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves a list of all the built-in policy set definitions that match the optional given $filter. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy set definitions whose category match the {value}. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions - /// - /// - /// Operation Id - /// PolicySetDefinitions_ListBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetAllAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListBuiltInRequest(filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListBuiltInNextPageRequest(nextLink, filter, top); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new TenantPolicySetDefinitionResource(Client, PolicySetDefinitionData.DeserializePolicySetDefinitionData(e)), _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics, Pipeline, "TenantPolicySetDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// This operation retrieves a list of all the built-in policy set definitions that match the optional given $filter. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy set definitions whose category match the {value}. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions - /// - /// - /// Operation Id - /// PolicySetDefinitions_ListBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. - /// Maximum number of records to return. When the $top filter is not provided, it will return 500 records. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetAll(string filter = null, int? top = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListBuiltInRequest(filter, top); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.CreateListBuiltInNextPageRequest(nextLink, filter, top); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new TenantPolicySetDefinitionResource(Client, PolicySetDefinitionData.DeserializePolicySetDefinitionData(e)), _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics, Pipeline, "TenantPolicySetDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> ExistsAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = await _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltInAsync(policySetDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Checks to see if the resource exists in azure. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response Exists(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.Exists"); - scope.Start(); - try - { - var response = _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltIn(policySetDefinitionName, cancellationToken: cancellationToken); - return Response.FromValue(response.Value != null, response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetIfExistsAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = await _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltInAsync(policySetDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new TenantPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Tries to get details for this resource from the service. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual NullableResponse GetIfExists(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName)); - - using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.GetIfExists"); - scope.Start(); - try - { - var response = _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltIn(policySetDefinitionName, cancellationToken: cancellationToken); - if (response.Value == null) - return new NoValueResponse(response.GetRawResponse()); - return Response.FromValue(new TenantPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetAll().GetEnumerator(); - } - - IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) - { - return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionResource.Serialization.cs deleted file mode 100644 index e2e25a534c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class TenantPolicySetDefinitionResource : IJsonModel - { - private static PolicySetDefinitionData s_dataDeserializationInstance; - private static PolicySetDefinitionData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - PolicySetDefinitionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - PolicySetDefinitionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionResource.cs deleted file mode 100644 index ca45c6dc6a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionResource.cs +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a TenantPolicySetDefinition along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetTenantPolicySetDefinitionResource method. - /// Otherwise you can get one from its parent resource using the GetTenantPolicySetDefinition method. - /// - public partial class TenantPolicySetDefinitionResource : ArmResource - { - /// Generate the resource identifier of a instance. - /// The policySetDefinitionName. - public static ResourceIdentifier CreateResourceIdentifier(string policySetDefinitionName) - { - var resourceId = $"/providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}"; - return new ResourceIdentifier(resourceId); - } - - private readonly ClientDiagnostics _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics; - private readonly PolicySetDefinitionsRestOperations _tenantPolicySetDefinitionPolicySetDefinitionsRestClient; - private readonly PolicySetDefinitionData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Authorization/policySetDefinitions"; - - /// Initializes a new instance of the class for mocking. - protected TenantPolicySetDefinitionResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The resource that is the target of operations. - internal TenantPolicySetDefinitionResource(ArmClient client, PolicySetDefinitionData data) : this(client, data.Id) - { - HasData = true; - _data = data; - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal TenantPolicySetDefinitionResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string tenantPolicySetDefinitionPolicySetDefinitionsApiVersion); - _tenantPolicySetDefinitionPolicySetDefinitionsRestClient = new PolicySetDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, tenantPolicySetDefinitionPolicySetDefinitionsApiVersion); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual PolicySetDefinitionData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// - /// This operation retrieves the built-in policy set definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual async Task> GetAsync(CancellationToken cancellationToken = default) - { - using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionResource.Get"); - scope.Start(); - try - { - var response = await _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltInAsync(Id.Name, cancellationToken).ConfigureAwait(false); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TenantPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// This operation retrieves the built-in policy set definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The cancellation token to use. - public virtual Response Get(CancellationToken cancellationToken = default) - { - using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionResource.Get"); - scope.Start(); - try - { - var response = _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltIn(Id.Name, cancellationToken); - if (response.Value == null) - throw new RequestFailedException(response.GetRawResponse()); - return Response.FromValue(new TenantPolicySetDefinitionResource(Client, response.Value), response.GetRawResponse()); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantResource.Serialization.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantResource.Serialization.cs deleted file mode 100644 index 7b9b360a83..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantResource.Serialization.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.ResourceManager.Resources -{ - public partial class TenantResource : IJsonModel - { - private static TenantData s_dataDeserializationInstance; - private static TenantData DataDeserializationInstance => s_dataDeserializationInstance ??= new(); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); - - TenantData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)DataDeserializationInstance).Create(ref reader, options); - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options, AzureResourceManagerContext.Default); - - TenantData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options, AzureResourceManagerContext.Default); - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)DataDeserializationInstance).GetFormatFromOptions(options); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantResource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantResource.cs deleted file mode 100644 index 1b1536a286..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Resources/Generated/TenantResource.cs +++ /dev/null @@ -1,505 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.Pipeline; -using Azure.ResourceManager.Resources.Models; - -namespace Azure.ResourceManager.Resources -{ - /// - /// A Class representing a Tenant along with the instance operations that can be performed on it. - /// If you have a you can construct a - /// from an instance of using the GetTenantResource method. - /// - public partial class TenantResource : ArmResource - { - private readonly ClientDiagnostics _tenantClientDiagnostics; - private readonly TenantsRestOperations _tenantRestClient; - private readonly ClientDiagnostics _resourceProviderProvidersClientDiagnostics; - private readonly ProvidersRestOperations _resourceProviderProvidersRestClient; - private readonly ClientDiagnostics _providersClientDiagnostics; - private readonly ProvidersRestOperations _providersRestClient; - private readonly TenantData _data; - - /// Gets the resource type for the operations. - public static readonly ResourceType ResourceType = "Microsoft.Resources/tenants"; - - /// Initializes a new instance of the class for mocking. - protected TenantResource() - { - } - - /// Initializes a new instance of the class. - /// The client parameters to use in these operations. - /// The identifier of the resource that is the target of operations. - internal TenantResource(ArmClient client, ResourceIdentifier id) : base(client, id) - { - _tenantClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceType, out string tenantApiVersion); - _tenantRestClient = new TenantsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, tenantApiVersion); - _resourceProviderProvidersClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceProviderResource.ResourceType.Namespace, Diagnostics); - TryGetApiVersion(ResourceProviderResource.ResourceType, out string resourceProviderProvidersApiVersion); - _resourceProviderProvidersRestClient = new ProvidersRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, resourceProviderProvidersApiVersion); - _providersClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ProviderConstants.DefaultProviderNamespace, Diagnostics); - _providersRestClient = new ProvidersRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint); -#if DEBUG - ValidateResourceId(Id); -#endif - } - - /// Gets whether or not the current instance has data. - public virtual bool HasData { get; } - - /// Gets the data representing this Feature. - /// Throws if there is no data loaded in the current instance. - public virtual TenantData Data - { - get - { - if (!HasData) - throw new InvalidOperationException("The current instance does not have data, you must call Get first."); - return _data; - } - } - - internal static void ValidateResourceId(ResourceIdentifier id) - { - if (id.ResourceType != ResourceType) - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); - } - - /// Gets a collection of TenantPolicyDefinitionResources in the Tenant. - /// An object representing collection of TenantPolicyDefinitionResources and their operations over a TenantPolicyDefinitionResource. - public virtual TenantPolicyDefinitionCollection GetTenantPolicyDefinitions() - { - return GetCachedClient(client => new TenantPolicyDefinitionCollection(client, Id)); - } - - /// - /// This operation retrieves the built-in policy definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetTenantPolicyDefinitionAsync(string policyDefinitionName, CancellationToken cancellationToken = default) - { - return await GetTenantPolicyDefinitions().GetAsync(policyDefinitionName, cancellationToken).ConfigureAwait(false); - } - - /// - /// This operation retrieves the built-in policy definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName} - /// - /// - /// Operation Id - /// PolicyDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the built-in policy definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetTenantPolicyDefinition(string policyDefinitionName, CancellationToken cancellationToken = default) - { - return GetTenantPolicyDefinitions().Get(policyDefinitionName, cancellationToken); - } - - /// Gets a collection of TenantPolicySetDefinitionResources in the Tenant. - /// An object representing collection of TenantPolicySetDefinitionResources and their operations over a TenantPolicySetDefinitionResource. - public virtual TenantPolicySetDefinitionCollection GetTenantPolicySetDefinitions() - { - return GetCachedClient(client => new TenantPolicySetDefinitionCollection(client, Id)); - } - - /// - /// This operation retrieves the built-in policy set definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetTenantPolicySetDefinitionAsync(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - return await GetTenantPolicySetDefinitions().GetAsync(policySetDefinitionName, cancellationToken).ConfigureAwait(false); - } - - /// - /// This operation retrieves the built-in policy set definition with the given name. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName} - /// - /// - /// Operation Id - /// PolicySetDefinitions_GetBuiltIn - /// - /// - /// Default Api Version - /// 2021-06-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The name of the policy set definition to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetTenantPolicySetDefinition(string policySetDefinitionName, CancellationToken cancellationToken = default) - { - return GetTenantPolicySetDefinitions().Get(policySetDefinitionName, cancellationToken); - } - - /// Gets a collection of DataPolicyManifestResources in the Tenant. - /// An object representing collection of DataPolicyManifestResources and their operations over a DataPolicyManifestResource. - public virtual DataPolicyManifestCollection GetDataPolicyManifests() - { - return GetCachedClient(client => new DataPolicyManifestCollection(client, Id)); - } - - /// - /// This operation retrieves the data policy manifest with the given policy mode. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetDataPolicyManifestAsync(string policyMode, CancellationToken cancellationToken = default) - { - return await GetDataPolicyManifests().GetAsync(policyMode, cancellationToken).ConfigureAwait(false); - } - - /// - /// This operation retrieves the data policy manifest with the given policy mode. - /// - /// - /// Request Path - /// /providers/Microsoft.Authorization/dataPolicyManifests/{policyMode} - /// - /// - /// Operation Id - /// DataPolicyManifests_GetByPolicyMode - /// - /// - /// Default Api Version - /// 2020-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The policy mode of the data policy manifest to get. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetDataPolicyManifest(string policyMode, CancellationToken cancellationToken = default) - { - return GetDataPolicyManifests().Get(policyMode, cancellationToken); - } - - /// Gets a collection of GenericResources in the Tenant. - /// An object representing collection of GenericResources and their operations over a GenericResource. - public virtual GenericResourceCollection GetGenericResources() - { - return GetCachedClient(client => new GenericResourceCollection(client, Id)); - } - - /// Gets a collection of SubscriptionResources in the Tenant. - /// An object representing collection of SubscriptionResources and their operations over a SubscriptionResource. - public virtual SubscriptionCollection GetSubscriptions() - { - return GetCachedClient(client => new SubscriptionCollection(client, Id)); - } - - /// - /// Gets details about a specified subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The ID of the target subscription. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual async Task> GetSubscriptionAsync(string subscriptionId, CancellationToken cancellationToken = default) - { - return await GetSubscriptions().GetAsync(subscriptionId, cancellationToken).ConfigureAwait(false); - } - - /// - /// Gets details about a specified subscription. - /// - /// - /// Request Path - /// /subscriptions/{subscriptionId} - /// - /// - /// Operation Id - /// Subscriptions_Get - /// - /// - /// Default Api Version - /// 2022-12-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The ID of the target subscription. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - [ForwardsClientCalls] - public virtual Response GetSubscription(string subscriptionId, CancellationToken cancellationToken = default) - { - return GetSubscriptions().Get(subscriptionId, cancellationToken); - } - - /// - /// Gets all resource providers for the tenant. - /// - /// - /// Request Path - /// /providers - /// - /// - /// Operation Id - /// Providers_ListAtTenantScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// An async collection of that may take multiple service requests to iterate over. - public virtual AsyncPageable GetTenantResourceProvidersAsync(string expand = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _resourceProviderProvidersRestClient.CreateListAtTenantScopeRequest(expand); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _resourceProviderProvidersRestClient.CreateListAtTenantScopeNextPageRequest(nextLink, expand); - return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => TenantResourceProvider.DeserializeTenantResourceProvider(e), _resourceProviderProvidersClientDiagnostics, Pipeline, "TenantResource.GetTenantResourceProviders", "value", "nextLink", cancellationToken); - } - - /// - /// Gets all resource providers for the tenant. - /// - /// - /// Request Path - /// /providers - /// - /// - /// Operation Id - /// Providers_ListAtTenantScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// Resource - /// - /// - /// - /// - /// The properties to include in the results. For example, use &$expand=metadata in the query string to retrieve resource provider metadata. To include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// A collection of that may take multiple service requests to iterate over. - public virtual Pageable GetTenantResourceProviders(string expand = null, CancellationToken cancellationToken = default) - { - HttpMessage FirstPageRequest(int? pageSizeHint) => _resourceProviderProvidersRestClient.CreateListAtTenantScopeRequest(expand); - HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _resourceProviderProvidersRestClient.CreateListAtTenantScopeNextPageRequest(nextLink, expand); - return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => TenantResourceProvider.DeserializeTenantResourceProvider(e), _resourceProviderProvidersClientDiagnostics, Pipeline, "TenantResource.GetTenantResourceProviders", "value", "nextLink", cancellationToken); - } - - /// - /// Gets the specified resource provider at the tenant level. - /// - /// - /// Request Path - /// /providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_GetAtTenantScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual async Task> GetTenantResourceProviderAsync(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var scope = _providersClientDiagnostics.CreateScope("TenantResource.GetTenantResourceProvider"); - scope.Start(); - try - { - var response = await _providersRestClient.GetAtTenantScopeAsync(resourceProviderNamespace, expand, cancellationToken).ConfigureAwait(false); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// Gets the specified resource provider at the tenant level. - /// - /// - /// Request Path - /// /providers/{resourceProviderNamespace} - /// - /// - /// Operation Id - /// Providers_GetAtTenantScope - /// - /// - /// Default Api Version - /// 2022-09-01 - /// - /// - /// - /// The namespace of the resource provider. - /// The $expand query parameter. For example, to include property aliases in response, use $expand=resourceTypes/aliases. - /// The cancellation token to use. - /// is an empty string, and was expected to be non-empty. - /// is null. - public virtual Response GetTenantResourceProvider(string resourceProviderNamespace, string expand = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(resourceProviderNamespace, nameof(resourceProviderNamespace)); - - using var scope = _providersClientDiagnostics.CreateScope("TenantResource.GetTenantResourceProvider"); - scope.Start(); - try - { - var response = _providersRestClient.GetAtTenantScope(resourceProviderNamespace, expand, cancellationToken); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/AppContextSwitchHelper.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/AppContextSwitchHelper.cs deleted file mode 100644 index 6b511aae6c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/AppContextSwitchHelper.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -#nullable enable - -namespace Azure.Core -{ - /// - /// Helper for interacting with AppConfig settings and their related Environment variable settings. - /// - internal static class AppContextSwitchHelper - { - /// - /// Determines if either an AppContext switch or its corresponding Environment Variable is set - /// - /// Name of the AppContext switch. - /// Name of the Environment variable. - /// If the AppContext switch has been set, returns the value of the switch. - /// If the AppContext switch has not been set, returns the value of the environment variable. - /// False if neither is set. - /// - public static bool GetConfigValue(string appContexSwitchName, string environmentVariableName) - { - // First check for the AppContext switch, giving it priority over the environment variable. - if (AppContext.TryGetSwitch(appContexSwitchName, out bool value)) - { - return value; - } - // AppContext switch wasn't used. Check the environment variable. - string? envVar = Environment.GetEnvironmentVariable(environmentVariableName); - if (envVar != null && (envVar.Equals("true", StringComparison.OrdinalIgnoreCase) || envVar.Equals("1"))) - { - return true; - } - - // Default to false. - return false; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/AsyncLockWithValue.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/AsyncLockWithValue.cs deleted file mode 100644 index 96aa1a559c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/AsyncLockWithValue.cs +++ /dev/null @@ -1,260 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; - -namespace Azure.Core -{ - /// - /// Primitive that combines async lock and value cache - /// - /// - internal sealed class AsyncLockWithValue - { - private readonly object _syncObj = new(); - private Queue>? _waiters; - private bool _isLocked; - private bool _hasValue; - private long _index; - private T? _value; - - public bool HasValue - { - get - { - lock (_syncObj) - { - return _hasValue; - } - } - } - - public AsyncLockWithValue() { } - - public AsyncLockWithValue(T value) - { - _hasValue = true; - _value = value; - } - - public bool TryGetValue(out T? value) - { - lock (_syncObj) - { - if (_hasValue) - { - value = _value; - return true; - } - } - - value = default; - return false; - } - - /// - /// Method that either returns cached value or acquire a lock. - /// If one caller has acquired a lock, other callers will be waiting for the lock to be released. - /// If value is set, lock is released and all waiters get that value. - /// If value isn't set, the next waiter in the queue will get the lock. - /// - /// - /// - /// - public async ValueTask GetLockOrValueAsync(bool async, CancellationToken cancellationToken = default) - { - TaskCompletionSource valueTcs; - lock (_syncObj) - { - // If there is a value, just return it - if (_hasValue) - { - return new LockOrValue(_value!); - } - - // If lock isn't acquire yet, acquire it and return to the caller - if (!_isLocked) - { - _isLocked = true; - _index = unchecked(_index + 1); - return new LockOrValue(this, _index); - } - - // Check cancellationToken before instantiating waiter - cancellationToken.ThrowIfCancellationRequested(); - - // If lock is already taken, create a waiter and wait either until value is set or lock can be acquired by this waiter - _waiters ??= new Queue>(); - // if async == false, valueTcs will be waited only in this thread and only synchronously, so RunContinuationsAsynchronously isn't needed. - valueTcs = new TaskCompletionSource(async ? TaskCreationOptions.RunContinuationsAsynchronously : TaskCreationOptions.None); - _waiters.Enqueue(valueTcs); - } - - try - { - if (async) - { - return await valueTcs.Task.AwaitWithCancellation(cancellationToken); - } - -#pragma warning disable AZC0104 // Use EnsureCompleted() directly on asynchronous method return value. -#pragma warning disable AZC0111 // DO NOT use EnsureCompleted in possibly asynchronous scope. - valueTcs.Task.Wait(cancellationToken); - return valueTcs.Task.EnsureCompleted(); -#pragma warning restore AZC0111 // DO NOT use EnsureCompleted in possibly asynchronous scope. -#pragma warning restore AZC0104 // Use EnsureCompleted() directly on asynchronous method return value. - } - catch (OperationCanceledException) - { - // Throw OperationCanceledException only if another thread hasn't set a value to this waiter - // by calling either Reset or SetValue - if (valueTcs.TrySetCanceled(cancellationToken)) - { - throw; - } - - return valueTcs.Task.Result; - } - } - - /// - /// Set value to the cache and to all the waiters - /// - /// - /// - private void SetValue(T value, in long lockIndex) - { - Queue> waiters; - lock (_syncObj) - { - if (lockIndex != _index) - { - throw new InvalidOperationException($"Disposed {nameof(LockOrValue)} tries to set value. Current index: {_index}, {nameof(LockOrValue)} index: {lockIndex}"); - } - - _value = value; - _hasValue = true; - _index = 0; - _isLocked = false; - if (_waiters == default) - { - return; - } - - waiters = _waiters; - _waiters = default; - } - - while (waiters.Count > 0) - { - waiters.Dequeue().TrySetResult(new LockOrValue(value)); - } - } - - /// - /// Release the lock and allow next waiter acquire it - /// - private void Reset(in long lockIndex) - { - UnlockOrGetNextWaiter(lockIndex, out var nextWaiter); - while (nextWaiter != default && !nextWaiter.TrySetResult(new LockOrValue(this, unchecked(lockIndex + 1)))) - { - UnlockOrGetNextWaiter(lockIndex, out nextWaiter); - } - } - - private void UnlockOrGetNextWaiter(in long lockIndex, out TaskCompletionSource? nextWaiter) - { - lock (_syncObj) - { - nextWaiter = default; - // If lock isn't acquired, just return - if (!_isLocked || lockIndex != _index) - { - return; - } - - _index = unchecked(lockIndex + 1); - - // If lock was acquired, but there are no waiters, unlock and return - if (_waiters == default) - { - _isLocked = false; - return; - } - - // Find the next waiter - while (_waiters.Count > 0) - { - nextWaiter = _waiters.Dequeue(); - if (!nextWaiter.Task.IsCompleted) - { - // Return the waiter only if it wasn't canceled already - return; - } - } - - // If no next waiter has been found, unlock and return - _isLocked = false; - } - } - - public readonly struct LockOrValue : IDisposable - { - private readonly AsyncLockWithValue? _owner; - private readonly T? _value; - private readonly long _index; - - /// - /// Returns true if lock contains the cached value. Otherwise false. - /// - public bool HasValue => _owner == default; - - /// - /// Returns cached value if it was set when lock has been created. Throws exception otherwise. - /// - /// Value isn't set. - public T Value => HasValue ? _value! : throw new InvalidOperationException("Value isn't set"); - - public LockOrValue(T value) - { - _owner = default; - _value = value; - _index = 0; - } - - public LockOrValue(AsyncLockWithValue owner, long index) - { - _owner = owner; - _index = index; - _value = default; - } - - /// - /// Set value to the cache and to all the waiters. - /// - /// - /// Value is set already. - public void SetValue(T value) - { - if (_owner != null) - { - _owner.SetValue(value, _index); - } - else - { - throw new InvalidOperationException("Value for the lock is set already"); - } - } - - public void Dispose() => _owner?.Reset(_index); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/AzureResourceProviderNamespaceAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/AzureResourceProviderNamespaceAttribute.cs deleted file mode 100644 index e9ac665a94..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/AzureResourceProviderNamespaceAttribute.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -namespace Azure.Core -{ - /// - /// This attribute should be set on all client assemblies with value of one of the resource providers - /// from the https://docs.microsoft.com/azure/azure-resource-manager/management/azure-services-resource-providers list. - /// - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] - internal class AzureResourceProviderNamespaceAttribute : Attribute - { - public string ResourceProviderNamespace { get; } - - public AzureResourceProviderNamespaceAttribute(string resourceProviderNamespace) - { - ResourceProviderNamespace = resourceProviderNamespace; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ClientDiagnostics.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ClientDiagnostics.cs deleted file mode 100644 index f9fc345937..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ClientDiagnostics.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; - -#nullable enable - -namespace Azure.Core.Pipeline -{ - internal class ClientDiagnostics : DiagnosticScopeFactory - { - /// - /// Initializes a new instance of the class. - /// - /// The customer provided client options object. - /// Flag controlling if - /// created by this for client method calls should be suppressed when called - /// by other Azure SDK client methods. It's recommended to set it to true for new clients; use default (null) - /// for backward compatibility reasons, or set it to false to explicitly disable suppression for specific cases. - /// The default value could change in the future, the flag should be only set to false if suppression for the client - /// should never be enabled. - public ClientDiagnostics(ClientOptions options, bool? suppressNestedClientActivities = null) - : this(options.GetType().Namespace!, - GetResourceProviderNamespace(options.GetType().Assembly), - options.Diagnostics, - suppressNestedClientActivities) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// Namespace of the client class, such as Azure.Storage or Azure.AppConfiguration. - /// Azure Resource Provider namespace of the Azure service SDK is primarily used for. - /// The customer provided client diagnostics options. - /// Flag controlling if - /// created by this for client method calls should be suppressed when called - /// by other Azure SDK client methods. It's recommended to set it to true for new clients, use default (null) for old clients - /// for backward compatibility reasons, or set it to false to explicitly disable suppression for specific cases. - /// The default value could change in the future, the flag should be only set to false if suppression for the client - /// should never be enabled. - public ClientDiagnostics(string optionsNamespace, string? providerNamespace, DiagnosticsOptions diagnosticsOptions, bool? suppressNestedClientActivities = null) - : base(optionsNamespace, providerNamespace, diagnosticsOptions.IsDistributedTracingEnabled, suppressNestedClientActivities.GetValueOrDefault(true), true) - { - } - - internal static HttpMessageSanitizer CreateMessageSanitizer(DiagnosticsOptions diagnostics) - { - return new HttpMessageSanitizer( - diagnostics.LoggedQueryParameters.ToArray(), - diagnostics.LoggedHeaderNames.ToArray()); - } - - internal static string? GetResourceProviderNamespace(Assembly assembly) - { - foreach (var customAttribute in assembly.GetCustomAttributesData()) - { - // Weak bind internal shared type - Type attributeType = customAttribute.AttributeType!; - if (attributeType.FullName == ("Azure.Core.AzureResourceProviderNamespaceAttribute")) - { - IList namedArguments = customAttribute.ConstructorArguments; - return namedArguments.Single().Value as string; - } - } - - return null; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/DiagnosticScope.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/DiagnosticScope.cs deleted file mode 100644 index c32bf2b8cb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/DiagnosticScope.cs +++ /dev/null @@ -1,448 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.Linq.Expressions; -using System.Net.Http; -using System.Reflection; - -namespace Azure.Core.Pipeline -{ - internal readonly struct DiagnosticScope : IDisposable - { - private const string AzureSdkScopeLabel = "az.sdk.scope"; - internal const string OpenTelemetrySchemaAttribute = "az.schema_url"; - - // we follow OpenTelemtery Semantic Conventions 1.23.0 - // https://github.com/open-telemetry/semantic-conventions/blob/v1.23.0 - internal const string OpenTelemetrySchemaVersion = "https://opentelemetry.io/schemas/1.23.0"; - private static readonly object AzureSdkScopeValue = bool.TrueString; - private readonly ActivityAdapter? _activityAdapter; - private readonly bool _suppressNestedClientActivities; - - internal DiagnosticScope(string scopeName, DiagnosticListener source, object? diagnosticSourceArgs, ActivitySource? activitySource, System.Diagnostics.ActivityKind kind, bool suppressNestedClientActivities) - { - // ActivityKind.Internal and Client both can represent public API calls depending on the SDK - _suppressNestedClientActivities = (kind == ActivityKind.Client || kind == System.Diagnostics.ActivityKind.Internal) ? suppressNestedClientActivities : false; - - // outer scope presence is enough to suppress any inner scope, regardless of inner scope configuation. - bool hasListeners; - hasListeners = activitySource?.HasListeners() ?? false; - IsEnabled = source.IsEnabled() || hasListeners; - - if (_suppressNestedClientActivities) - { - IsEnabled &= !AzureSdkScopeValue.Equals(Activity.Current?.GetCustomProperty(AzureSdkScopeLabel)); - } - - _activityAdapter = IsEnabled ? new ActivityAdapter( - activitySource: activitySource, - diagnosticSource: source, - activityName: scopeName, - kind: kind, - diagnosticSourceArgs: diagnosticSourceArgs) : null; - } - - public bool IsEnabled { get; } - - public void AddAttribute(string name, string? value) - { - if (value != null) - { - _activityAdapter?.AddTag(name, value); - } - } - - public void AddIntegerAttribute(string name, int value) - { - _activityAdapter?.AddTag(name, value); - } - - public void AddLongAttribute(string name, long value) - { - _activityAdapter?.AddTag(name, value); - } - - public void AddAttribute(string name, T value, Func format) - { - if (_activityAdapter != null && value != null) - { - var formattedValue = format(value); - _activityAdapter.AddTag(name, formattedValue); - } - } - - /// - /// Adds a link to the scope. This must be called before has been called for the DiagnosticScope. - /// - /// The traceparent for the link. - /// The tracestate for the link. - /// Optional attributes to associate with the link. - public void AddLink(string traceparent, string? tracestate, IDictionary? attributes = null) - { - _activityAdapter?.AddLink(traceparent, tracestate, attributes); - } - - public void Start() - { - Activity? started = _activityAdapter?.Start(); - if (_suppressNestedClientActivities) - { - started?.SetCustomProperty(AzureSdkScopeLabel, AzureSdkScopeValue); - } - } - - public void SetDisplayName(string displayName) - { - _activityAdapter?.SetDisplayName(displayName); - } - - public void SetStartTime(DateTime dateTime) - { - _activityAdapter?.SetStartTime(dateTime); - } - - /// - /// Sets the trace context for the current scope. - /// - /// The trace parent to set for the current scope. - /// The trace state to set for the current scope. - public void SetTraceContext(string traceparent, string? tracestate = default) - { - _activityAdapter?.SetTraceContext(traceparent, tracestate); - } - - public void Dispose() - { - // Reverse the Start order - _activityAdapter?.Dispose(); - } - - /// - /// Marks the scope as failed. - /// - /// The exception to associate with the failed scope. - public void Failed(Exception exception) - { - if (exception is RequestFailedException requestFailedException) - { - // TODO (limolkova) when we start targeting .NET 8 we should put - // requestFailedException.InnerException.HttpRequestError into error.type - - string? errorCode = string.IsNullOrEmpty(requestFailedException.ErrorCode) ? null : requestFailedException.ErrorCode; - _activityAdapter?.MarkFailed(exception, errorCode); - } - else - { - _activityAdapter?.MarkFailed(exception, null); - } - } - - /// - /// Marks the scope as failed with low-cardinality error.type attribute. - /// - /// Error code to associate with the failed scope. - public void Failed(string errorCode) - { - _activityAdapter?.MarkFailed((Exception?)null, errorCode); - } - - private class DiagnosticActivity : Activity - { -#pragma warning disable 109 // extra new modifier - public new IEnumerable Links { get; set; } = Array.Empty(); -#pragma warning restore 109 - - public DiagnosticActivity(string operationName) : base(operationName) - { - } - } - - private class ActivityAdapter : IDisposable - { - private readonly ActivitySource? _activitySource; - private readonly DiagnosticSource _diagnosticSource; - private readonly string _activityName; - private readonly System.Diagnostics.ActivityKind _kind; - private readonly object? _diagnosticSourceArgs; - - private Activity? _currentActivity; - private Activity? _sampleOutActivity; - - private ActivityTagsCollection? _tagCollection; - private DateTimeOffset _startTime; - private List? _links; - private string? _traceparent; - private string? _tracestate; - private string? _displayName; - - public ActivityAdapter(ActivitySource? activitySource, DiagnosticSource diagnosticSource, string activityName, System.Diagnostics.ActivityKind kind, object? diagnosticSourceArgs) - { - _activitySource = activitySource; - _diagnosticSource = diagnosticSource; - _activityName = activityName; - _kind = kind; - _diagnosticSourceArgs = diagnosticSourceArgs; - } - - public void AddTag(string name, object value) - { - if (_sampleOutActivity == null) - { - if (_currentActivity == null) - { - // Activity is not started yet, add the value to the collection - // that is going to be passed to StartActivity - _tagCollection ??= new ActivityTagsCollection(); - _tagCollection[name] = value!; - } - else - { - AddObjectTag(name, value); - } - } - } - - private IReadOnlyList GetDiagnosticSourceLinkCollection() - { - if (_links == null) - { - return Array.Empty(); - } - - var linkCollection = new List(); - - foreach (var link in _links) - { - var activity = new Activity("LinkedActivity"); - activity.SetIdFormat(ActivityIdFormat.W3C); - if (link.Context != default) - { - activity.SetParentId(ActivityContextToTraceParent(link.Context)); - activity.TraceStateString = link.Context.TraceState; - } - - if (link.Tags != null) - { - foreach (var tag in link.Tags) - { - if (tag.Value != null) - { - // old code path, only string attributes are supported - activity.AddTag(tag.Key, tag.Value.ToString()); - } - } - } - linkCollection.Add(activity); - } - - return linkCollection; - } - - private static string ActivityContextToTraceParent(ActivityContext context) - { - string flags = (context.TraceFlags == ActivityTraceFlags.None) ? "00" : "01"; - return "00-" + context.TraceId + "-" + context.SpanId + "-" + flags; - } - - public void AddLink(string traceparent, string? tracestate, IDictionary? attributes) - { - // if context is invalid, we should still add a link since it contains attributes - // so we let ActivityLink deal with the default context. - // This is otel spec requirement and default context is allowed on links. - ActivityContext.TryParse(traceparent, tracestate, out var context); - var linkedActivity = new ActivityLink(context, attributes == null ? null : new ActivityTagsCollection(attributes)); - _links ??= new List(); - _links.Add(linkedActivity); - } - - public Activity? Start() - { - _currentActivity = StartActivitySourceActivity(); - if (_currentActivity != null) - { - if (!_currentActivity.IsAllDataRequested) - { - _sampleOutActivity = _currentActivity; - _currentActivity = null; - - return null; - } - - _currentActivity.SetTag(OpenTelemetrySchemaAttribute, OpenTelemetrySchemaVersion); - } - else - { - if (!_diagnosticSource.IsEnabled(_activityName, _diagnosticSourceArgs)) - { - return null; - } - - switch (_kind) - { - case ActivityKind.Internal: - AddTag("kind", "internal"); - break; - case ActivityKind.Server: - AddTag("kind", "server"); - break; - case ActivityKind.Client: - AddTag("kind", "client"); - break; - case ActivityKind.Producer: - AddTag("kind", "producer"); - break; - case ActivityKind.Consumer: - AddTag("kind", "consumer"); - break; - } - - _currentActivity = new DiagnosticActivity(_activityName) - { - Links = GetDiagnosticSourceLinkCollection(), - }; - _currentActivity.SetIdFormat(ActivityIdFormat.W3C); - - if (_startTime != default) - { - _currentActivity.SetStartTime(_startTime.UtcDateTime); - } - - if (_tagCollection != null) - { - foreach (var tag in _tagCollection) - { - AddObjectTag(tag.Key, tag.Value!); - } - } - - if (_traceparent != null) - { - _currentActivity.SetParentId(_traceparent); - } - - if (_tracestate != null) - { - _currentActivity.TraceStateString = _tracestate; - } - - _currentActivity.Start(); - } - - if (_displayName != null) - { - _currentActivity.DisplayName = _displayName; - } - - return _currentActivity; - } - - public void SetDisplayName(string displayName) - { - _displayName = displayName; - if (_currentActivity != null) - { - _currentActivity.DisplayName = _displayName; - } - } - - private Activity? StartActivitySourceActivity() - { - if (_activitySource == null) - { - return null; - } - // TODO(limolkova) set isRemote to true once we switch to DiagnosticSource 7.0 - ActivityContext.TryParse(_traceparent, _tracestate, out ActivityContext context); - return _activitySource.StartActivity(_activityName, _kind, context, _tagCollection, _links, _startTime); - } - - public void SetStartTime(DateTime startTime) - { - _startTime = startTime; - _currentActivity?.SetStartTime(startTime); - } - - public void MarkFailed(T? exception, string? errorCode) - { - if (errorCode == null && exception != null) - { - errorCode = exception.GetType().FullName; - } - - errorCode ??= "_OTHER"; - - // SetStatus is only defined in NET 6 or greater - _currentActivity?.SetTag("error.type", errorCode); - _currentActivity?.SetStatus(ActivityStatusCode.Error, exception?.ToString()); - } - - public void SetTraceContext(string traceparent, string? tracestate) - { - if (_currentActivity != null) - { - throw new InvalidOperationException("Traceparent can not be set after the activity is started."); - } - _traceparent = traceparent; - _tracestate = tracestate; - } - - private void AddObjectTag(string name, object value) - { - if (_activitySource?.HasListeners() == true) - { - _currentActivity?.SetTag(name, value); - } - else - { - _currentActivity?.AddTag(name, value.ToString()); - } - } - - public void Dispose() - { - var activity = _currentActivity ?? _sampleOutActivity; - if (activity == null) - { - return; - } - - if (activity.Duration == TimeSpan.Zero) - activity.SetEndTime(DateTime.UtcNow); - - activity.Dispose(); - - _currentActivity = null; - _sampleOutActivity = null; - } - } - } - -#pragma warning disable SA1507 // File can not contain multiple types - /// - /// Until Activity Source is no longer considered experimental. - /// - internal static class ActivityExtensions - { - static ActivityExtensions() - { - ResetFeatureSwitch(); - } - - public static bool SupportsActivitySource { get; private set; } - - public static void ResetFeatureSwitch() - { - SupportsActivitySource = AppContextSwitchHelper.GetConfigValue( - "Azure.Experimental.EnableActivitySource", - "AZURE_EXPERIMENTAL_ENABLE_ACTIVITY_SOURCE"); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/DiagnosticScopeFactory.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/DiagnosticScopeFactory.cs deleted file mode 100644 index 5e1d9c556e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/DiagnosticScopeFactory.cs +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Threading; - -#nullable enable - -namespace Azure.Core.Pipeline -{ -#pragma warning disable CA1001 // Types that own disposable fields should be disposable - internal class DiagnosticScopeFactory -#pragma warning restore CA1001 // Types that own disposable fields should be disposable - { - private static Dictionary? _listeners; - private readonly string? _resourceProviderNamespace; - private readonly DiagnosticListener? _source; - private readonly bool _suppressNestedClientActivities; - private readonly bool _isStable; - private static readonly ConcurrentDictionary ActivitySources = new(); - - /// - /// Creates diagnostic scope factory. - /// - /// The namespace which is used as a prefix for all ActivitySources created by the factory and the name of DiagnosticSource (when used). - /// Azure resource provider namespace. - /// Flag indicating if distributed tracing is enabled. - /// Flag indicating if nested Azure SDK activities describing public API calls should be suppressed. - /// Whether instrumentation is considered stable. When false, experimental feature flag controls if tracing is enabled. - public DiagnosticScopeFactory(string clientNamespace, string? resourceProviderNamespace, bool isActivityEnabled, bool suppressNestedClientActivities = true, bool isStable = false) - { - _resourceProviderNamespace = resourceProviderNamespace; - IsActivityEnabled = isActivityEnabled; - _suppressNestedClientActivities = suppressNestedClientActivities; - _isStable = isStable; - - if (IsActivityEnabled) - { - var listeners = LazyInitializer.EnsureInitialized(ref _listeners); - - lock (listeners!) - { - if (!listeners.TryGetValue(clientNamespace, out _source)) - { - _source = new DiagnosticListener(clientNamespace); - listeners[clientNamespace] = _source; - } - } - } - } - - public bool IsActivityEnabled { get; } - - public DiagnosticScope CreateScope(string name, System.Diagnostics.ActivityKind kind = ActivityKind.Internal) - { - if (_source == null) - { - return default; - } - - var scope = new DiagnosticScope( - scopeName: name, - source: _source, - diagnosticSourceArgs: null, - activitySource: GetActivitySource(_source.Name, name), - kind: kind, - suppressNestedClientActivities: _suppressNestedClientActivities); - - if (_resourceProviderNamespace != null) - { - scope.AddAttribute("az.namespace", _resourceProviderNamespace); - } - return scope; - } - - /// - /// This method combines client namespace and operation name into an ActivitySource name and creates the activity source. - /// For example: - /// ns: Azure.Storage.Blobs - /// name: BlobClient.DownloadTo - /// result Azure.Storage.Blobs.BlobClient - /// - private ActivitySource? GetActivitySource(string ns, string name) - { - bool enabled = _isStable; - enabled |= ActivityExtensions.SupportsActivitySource; - - if (!enabled) - { - return null; - } - - int indexOfDot = name.IndexOf(".", StringComparison.OrdinalIgnoreCase); - string clientName = ns + "." + ((indexOfDot < 0) ? name : name.Substring(0, indexOfDot)); - - return ActivitySources.GetOrAdd(clientName, static n => new ActivitySource(n)); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/FixedDelayWithNoJitterStrategy.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/FixedDelayWithNoJitterStrategy.cs deleted file mode 100644 index 1051e56b3f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/FixedDelayWithNoJitterStrategy.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -#nullable enable - -namespace Azure.Core -{ - /// - /// A delay strategy that uses a fixed delay with no jitter applied. This is used by data plane LROs. - /// - internal class FixedDelayWithNoJitterStrategy : DelayStrategy - { - private static readonly TimeSpan DefaultDelay = TimeSpan.FromSeconds(1); - private readonly TimeSpan _delay; - - public FixedDelayWithNoJitterStrategy(TimeSpan? suggestedDelay = default) : base(suggestedDelay.HasValue ? Max(suggestedDelay.Value, DefaultDelay) : DefaultDelay, 0) - { - _delay = suggestedDelay.HasValue ? Max(suggestedDelay.Value, DefaultDelay) : DefaultDelay; - } - - protected override TimeSpan GetNextDelayCore(Response? response, int retryNumber) => - _delay; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ForwardsClientCallsAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ForwardsClientCallsAttribute.cs deleted file mode 100644 index e9e933541b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ForwardsClientCallsAttribute.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -namespace Azure.Core -{ - /// - /// Marks methods that call methods on other client and don't need their diagnostics verified. - /// - [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] - internal class ForwardsClientCallsAttribute : Attribute - { - /// - /// Creates a new instance of . - /// - public ForwardsClientCallsAttribute() - : this(false) - { - } - - /// - /// Creates a new instance of . - /// - /// Sets whether or not diagnostic scope validation should happen. - public ForwardsClientCallsAttribute(bool skipChecks) - { - SkipChecks = skipChecks; - } - - /// - /// Gets whether or not we should validate DiagnosticScope for this API. - /// In the case where there is an internal API that makes the Azure API call and a public API that uses it we need ForwardsClientCalls. - /// If the public API will cache the results then the diagnostic scope will not always be created because an Azure API is not always called. - /// In this case we need to turn off this validation for this API only. - /// - public bool SkipChecks { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/HashCodeBuilder.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/HashCodeBuilder.cs deleted file mode 100644 index a6a76f93f8..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/HashCodeBuilder.cs +++ /dev/null @@ -1,387 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Runtime.CompilerServices; - -#nullable enable - -namespace Azure.Core -{ - /// - /// Copied from https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/HashCode.cs. - /// - internal struct HashCodeBuilder - { - private static readonly uint s_seed = GenerateGlobalSeed(); - - private const uint Prime1 = 2654435761U; - private const uint Prime2 = 2246822519U; - private const uint Prime3 = 3266489917U; - private const uint Prime4 = 668265263U; - private const uint Prime5 = 374761393U; - - private uint _v1, _v2, _v3, _v4; - private uint _queue1, _queue2, _queue3; - private uint _length; - - private static uint GenerateGlobalSeed() - { - return (uint)new Random().Next(); - } - - public static int Combine(T1 value1) - { - // Provide a way of diffusing bits from something with a limited - // input hash space. For example, many enums only have a few - // possible hashes, only using the bottom few bits of the code. Some - // collections are built on the assumption that hashes are spread - // over a larger space, so diffusing the bits may help the - // collection work more efficiently. - - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - - uint hash = MixEmptyState(); - hash += 4; - - hash = QueueRound(hash, hc1); - - hash = MixFinal(hash); - return (int)hash; - } - - public static int Combine(T1 value1, T2 value2) - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - - uint hash = MixEmptyState(); - hash += 8; - - hash = QueueRound(hash, hc1); - hash = QueueRound(hash, hc2); - - hash = MixFinal(hash); - return (int)hash; - } - - public static int Combine(T1 value1, T2 value2, T3 value3) - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - - uint hash = MixEmptyState(); - hash += 12; - - hash = QueueRound(hash, hc1); - hash = QueueRound(hash, hc2); - hash = QueueRound(hash, hc3); - - hash = MixFinal(hash); - return (int)hash; - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4) - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - uint hash = MixState(v1, v2, v3, v4); - hash += 16; - - hash = MixFinal(hash); - return (int)hash; - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5) - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - uint hc5 = (uint)(value5?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - uint hash = MixState(v1, v2, v3, v4); - hash += 20; - - hash = QueueRound(hash, hc5); - - hash = MixFinal(hash); - return (int)hash; - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6) - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - uint hc5 = (uint)(value5?.GetHashCode() ?? 0); - uint hc6 = (uint)(value6?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - uint hash = MixState(v1, v2, v3, v4); - hash += 24; - - hash = QueueRound(hash, hc5); - hash = QueueRound(hash, hc6); - - hash = MixFinal(hash); - return (int)hash; - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7) - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - uint hc5 = (uint)(value5?.GetHashCode() ?? 0); - uint hc6 = (uint)(value6?.GetHashCode() ?? 0); - uint hc7 = (uint)(value7?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - uint hash = MixState(v1, v2, v3, v4); - hash += 28; - - hash = QueueRound(hash, hc5); - hash = QueueRound(hash, hc6); - hash = QueueRound(hash, hc7); - - hash = MixFinal(hash); - return (int)hash; - } - - public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7, T8 value8) - { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); - uint hc2 = (uint)(value2?.GetHashCode() ?? 0); - uint hc3 = (uint)(value3?.GetHashCode() ?? 0); - uint hc4 = (uint)(value4?.GetHashCode() ?? 0); - uint hc5 = (uint)(value5?.GetHashCode() ?? 0); - uint hc6 = (uint)(value6?.GetHashCode() ?? 0); - uint hc7 = (uint)(value7?.GetHashCode() ?? 0); - uint hc8 = (uint)(value8?.GetHashCode() ?? 0); - - Initialize(out uint v1, out uint v2, out uint v3, out uint v4); - - v1 = Round(v1, hc1); - v2 = Round(v2, hc2); - v3 = Round(v3, hc3); - v4 = Round(v4, hc4); - - v1 = Round(v1, hc5); - v2 = Round(v2, hc6); - v3 = Round(v3, hc7); - v4 = Round(v4, hc8); - - uint hash = MixState(v1, v2, v3, v4); - hash += 32; - - hash = MixFinal(hash); - return (int)hash; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void Initialize(out uint v1, out uint v2, out uint v3, out uint v4) - { - v1 = s_seed + Prime1 + Prime2; - v2 = s_seed + Prime2; - v3 = s_seed; - v4 = s_seed - Prime1; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint Round(uint hash, uint input) - { - return RotateLeft(hash + input * Prime2, 13) * Prime1; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint QueueRound(uint hash, uint queuedValue) - { - return RotateLeft(hash + queuedValue * Prime3, 17) * Prime4; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint MixState(uint v1, uint v2, uint v3, uint v4) - { - return RotateLeft(v1, 1) + RotateLeft(v2, 7) + RotateLeft(v3, 12) + RotateLeft(v4, 18); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static uint RotateLeft(uint value, int offset) - => (value << offset) | (value >> (64 - offset)); - - private static uint MixEmptyState() - { - return s_seed + Prime5; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static uint MixFinal(uint hash) - { - hash ^= hash >> 15; - hash *= Prime2; - hash ^= hash >> 13; - hash *= Prime3; - hash ^= hash >> 16; - return hash; - } - - public void Add(T value) - { - Add(value?.GetHashCode() ?? 0); - } - - public void Add(T value, IEqualityComparer? comparer) - { - Add(value is null ? 0 : (comparer?.GetHashCode(value) ?? value.GetHashCode())); - } - - private void Add(int value) - { - // The original xxHash works as follows: - // 0. Initialize immediately. We can't do this in a struct (no - // default ctor). - // 1. Accumulate blocks of length 16 (4 uints) into 4 accumulators. - // 2. Accumulate remaining blocks of length 4 (1 uint) into the - // hash. - // 3. Accumulate remaining blocks of length 1 into the hash. - - // There is no need for #3 as this type only accepts ints. _queue1, - // _queue2 and _queue3 are basically a buffer so that when - // ToHashCode is called we can execute #2 correctly. - - // We need to initialize the xxHash32 state (_v1 to _v4) lazily (see - // #0) nd the last place that can be done if you look at the - // original code is just before the first block of 16 bytes is mixed - // in. The xxHash32 state is never used for streams containing fewer - // than 16 bytes. - - // To see what's really going on here, have a look at the Combine - // methods. - - uint val = (uint)value; - - // Storing the value of _length locally shaves of quite a few bytes - // in the resulting machine code. - uint previousLength = _length++; - uint position = previousLength % 4; - - // Switch can't be inlined. - - if (position == 0) - _queue1 = val; - else if (position == 1) - _queue2 = val; - else if (position == 2) - _queue3 = val; - else // position == 3 - { - if (previousLength == 3) - Initialize(out _v1, out _v2, out _v3, out _v4); - - _v1 = Round(_v1, _queue1); - _v2 = Round(_v2, _queue2); - _v3 = Round(_v3, _queue3); - _v4 = Round(_v4, val); - } - } - - public int ToHashCode() - { - // Storing the value of _length locally shaves of quite a few bytes - // in the resulting machine code. - uint length = _length; - - // position refers to the *next* queue position in this method, so - // position == 1 means that _queue1 is populated; _queue2 would have - // been populated on the next call to Add. - uint position = length % 4; - - // If the length is less than 4, _v1 to _v4 don't contain anything - // yet. xxHash32 treats this differently. - - uint hash = length < 4 ? MixEmptyState() : MixState(_v1, _v2, _v3, _v4); - - // _length is incremented once per Add(Int32) and is therefore 4 - // times too small (xxHash length is in bytes, not ints). - - hash += length * 4; - - // Mix what remains in the queue - - // Switch can't be inlined right now, so use as few branches as - // possible by manually excluding impossible scenarios (position > 1 - // is always false if position is not > 0). - if (position > 0) - { - hash = QueueRound(hash, _queue1); - if (position > 1) - { - hash = QueueRound(hash, _queue2); - if (position > 2) - hash = QueueRound(hash, _queue3); - } - } - - hash = MixFinal(hash); - return (int)hash; - } - -#pragma warning disable 0809 - // Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - // Disallowing GetHashCode and Equals is by design - - // * We decided to not override GetHashCode() to produce the hash code - // as this would be weird, both naming-wise as well as from a - // behavioral standpoint (GetHashCode() should return the object's - // hash code, not the one being computed). - - // * Even though ToHashCode() can be called safely multiple times on - // this implementation, it is not part of the contract. If the - // implementation has to change in the future we don't want to worry - // about people who might have incorrectly used this type. - - [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes. Use ToHashCode to retrieve the computed hash code.", error: true)] - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => throw new NotSupportedException(); - - [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes.", error: true)] - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object? obj) => throw new NotSupportedException(); -#pragma warning restore 0809 - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/HttpMessageSanitizer.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/HttpMessageSanitizer.cs deleted file mode 100644 index 36becf22a5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/HttpMessageSanitizer.cs +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -#nullable enable - -using System; -using System.Collections.Generic; -using System.Text; -using System.Linq; - -namespace Azure.Core; - -internal class HttpMessageSanitizer -{ - private const string LogAllValue = "*"; - private readonly bool _logAllHeaders; - private readonly bool _logFullQueries; - private readonly string[] _allowedQueryParameters; - private readonly string _redactedPlaceholder; - private readonly HashSet _allowedHeaders; - - [ThreadStatic] - private static StringBuilder? s_cachedStringBuilder; - private const int MaxCachedStringBuilderCapacity = 1024; - - internal static HttpMessageSanitizer Default = new HttpMessageSanitizer(Array.Empty(), Array.Empty()); - - public HttpMessageSanitizer(string[] allowedQueryParameters, string[] allowedHeaders, string redactedPlaceholder = "REDACTED") - { - _logAllHeaders = allowedHeaders.Contains(LogAllValue); - _logFullQueries = allowedQueryParameters.Contains(LogAllValue); - - _allowedQueryParameters = allowedQueryParameters; - _redactedPlaceholder = redactedPlaceholder; - _allowedHeaders = new HashSet(allowedHeaders, StringComparer.InvariantCultureIgnoreCase); - } - - public string SanitizeHeader(string name, string value) - { - if (_logAllHeaders || _allowedHeaders.Contains(name)) - { - return value; - } - - return _redactedPlaceholder; - } - - public string SanitizeUrl(string url) - { - if (_logFullQueries) - { - return url; - } - -#if NET5_0_OR_GREATER - int indexOfQuerySeparator = url.IndexOf('?', StringComparison.Ordinal); -#else - int indexOfQuerySeparator = url.IndexOf('?'); -#endif - - if (indexOfQuerySeparator == -1) - { - return url; - } - - // PERF: Avoid allocations in this heavily-used method: - // 1. Use ReadOnlySpan to avoid creating substrings. - // 2. Defer creating a StringBuilder until absolutely necessary. - // 3. Use a rented StringBuilder to avoid allocating a new one - // each time. - - // Create the StringBuilder only when necessary (when we encounter - // a query parameter that needs to be redacted) - StringBuilder? stringBuilder = null; - - // Keeps track of the number of characters we've processed so far - // so that, if we need to create a StringBuilder, we know how many - // characters to copy over from the original URL. - int lengthSoFar = indexOfQuerySeparator + 1; - - ReadOnlySpan query = url.AsSpan(indexOfQuerySeparator + 1); // +1 to skip the '?' - - while (query.Length > 0) - { - int endOfParameterValue = query.IndexOf('&'); - int endOfParameterName = query.IndexOf('='); - bool noValue = false; - - // Check if we have parameter without value - if ((endOfParameterValue == -1 && endOfParameterName == -1) || - (endOfParameterValue != -1 && (endOfParameterName == -1 || endOfParameterName > endOfParameterValue))) - { - endOfParameterName = endOfParameterValue; - noValue = true; - } - - if (endOfParameterName == -1) - { - endOfParameterName = query.Length; - } - - if (endOfParameterValue == -1) - { - endOfParameterValue = query.Length; - } - else - { - // include the separator - endOfParameterValue++; - } - - ReadOnlySpan parameterName = query.Slice(0, endOfParameterName); - - bool isAllowed = false; - foreach (string name in _allowedQueryParameters) - { - if (parameterName.Equals(name.AsSpan(), StringComparison.OrdinalIgnoreCase)) - { - isAllowed = true; - break; - } - } - - int valueLength = endOfParameterValue; - int nameLength = endOfParameterName; - - if (isAllowed || noValue) - { - if (stringBuilder is null) - { - lengthSoFar += valueLength; - } - else - { - AppendReadOnlySpan(stringBuilder, query.Slice(0, valueLength)); - } - } - else - { - // Encountered a query value that needs to be redacted. - // Create the StringBuilder if we haven't already. - stringBuilder ??= RentStringBuilder(url.Length).Append(url, 0, lengthSoFar); - - AppendReadOnlySpan(stringBuilder, query.Slice(0, nameLength)) - .Append('=') - .Append(_redactedPlaceholder); - - if (query[endOfParameterValue - 1] == '&') - { - stringBuilder.Append('&'); - } - } - - query = query.Slice(valueLength); - } - - return stringBuilder is null ? url : ToStringAndReturnStringBuilder(stringBuilder); - - static StringBuilder AppendReadOnlySpan(StringBuilder builder, ReadOnlySpan span) - { -#if NET6_0_OR_GREATER - return builder.Append(span); -#else - foreach (char c in span) - { - builder.Append(c); - } - - return builder; -#endif - } - } - - private static StringBuilder RentStringBuilder(int capacity) - { - if (capacity <= MaxCachedStringBuilderCapacity) - { - StringBuilder? builder = s_cachedStringBuilder; - if (builder is not null && builder.Capacity >= capacity) - { - s_cachedStringBuilder = null; - return builder; - } - } - - return new StringBuilder(capacity); - } - - private static string ToStringAndReturnStringBuilder(StringBuilder builder) - { - string result = builder.ToString(); - if (builder.Capacity <= MaxCachedStringBuilderCapacity) - { - s_cachedStringBuilder = builder.Clear(); - } - - return result; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/HttpPipelineExtensions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/HttpPipelineExtensions.cs deleted file mode 100644 index 231f13cf53..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/HttpPipelineExtensions.cs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; - -namespace Azure.Core -{ - internal static class HttpPipelineExtensions - { - public static async ValueTask ProcessMessageAsync(this HttpPipeline pipeline, HttpMessage message, RequestContext? requestContext, CancellationToken cancellationToken = default) - { - var (userCt, statusOption) = ApplyRequestContext(requestContext); - if (!userCt.CanBeCanceled || !cancellationToken.CanBeCanceled) - { - await pipeline.SendAsync(message, cancellationToken.CanBeCanceled ? cancellationToken : userCt).ConfigureAwait(false); - } - else - { - using var cts = CancellationTokenSource.CreateLinkedTokenSource(userCt, cancellationToken); - await pipeline.SendAsync(message, cts.Token).ConfigureAwait(false); - } - - if (!message.Response.IsError || statusOption == ErrorOptions.NoThrow) - { - return message.Response; - } - - throw new RequestFailedException(message.Response); - } - - public static Response ProcessMessage(this HttpPipeline pipeline, HttpMessage message, RequestContext? requestContext, CancellationToken cancellationToken = default) - { - var (userCt, statusOption) = ApplyRequestContext(requestContext); - if (!userCt.CanBeCanceled || !cancellationToken.CanBeCanceled) - { - pipeline.Send(message, cancellationToken.CanBeCanceled ? cancellationToken : userCt); - } - else - { - using var cts = CancellationTokenSource.CreateLinkedTokenSource(userCt, cancellationToken); - pipeline.Send(message, cts.Token); - } - - if (!message.Response.IsError || statusOption == ErrorOptions.NoThrow) - { - return message.Response; - } - - throw new RequestFailedException(message.Response); - } - - public static async ValueTask> ProcessHeadAsBoolMessageAsync(this HttpPipeline pipeline, HttpMessage message, ClientDiagnostics clientDiagnostics, RequestContext? requestContext) - { - var response = await pipeline.ProcessMessageAsync(message, requestContext).ConfigureAwait(false); - switch (response.Status) - { - case >= 200 and < 300: - return Response.FromValue(true, response); - case >= 400 and < 500: - return Response.FromValue(false, response); - default: - return new ErrorResponse(response, new RequestFailedException(response)); - } - } - - public static Response ProcessHeadAsBoolMessage(this HttpPipeline pipeline, HttpMessage message, ClientDiagnostics clientDiagnostics, RequestContext? requestContext) - { - var response = pipeline.ProcessMessage(message, requestContext); - switch (response.Status) - { - case >= 200 and < 300: - return Response.FromValue(true, response); - case >= 400 and < 500: - return Response.FromValue(false, response); - default: - return new ErrorResponse(response, new RequestFailedException(response)); - } - } - - private static (CancellationToken CancellationToken, ErrorOptions ErrorOptions) ApplyRequestContext(RequestContext? requestContext) - { - if (requestContext == null) - { - return (CancellationToken.None, ErrorOptions.Default); - } - - return (requestContext.CancellationToken, requestContext.ErrorOptions); - } - - internal class ErrorResponse : Response - { - private readonly Response _response; - private readonly RequestFailedException _exception; - - public ErrorResponse(Response response, RequestFailedException exception) - { - _response = response; - _exception = exception; - } - - public override T Value { get => throw _exception; } - - public override Response GetRawResponse() => _response; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/IOperationSource.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/IOperationSource.cs deleted file mode 100644 index 1be2f9b733..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/IOperationSource.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.Threading; -using System.Threading.Tasks; - -namespace Azure.Core -{ - internal interface IOperationSource - { - T CreateResult(Response response, CancellationToken cancellationToken); - ValueTask CreateResultAsync(Response response, CancellationToken cancellationToken); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/IUtf8JsonSerializable.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/IUtf8JsonSerializable.cs deleted file mode 100644 index 5653e46093..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/IUtf8JsonSerializable.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System.Text.Json; - -namespace Azure.Core -{ - internal interface IUtf8JsonSerializable - { - void Write(Utf8JsonWriter writer); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/InitializationConstructorAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/InitializationConstructorAttribute.cs deleted file mode 100644 index d087b58c2a..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/InitializationConstructorAttribute.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -namespace Azure.Core -{ - /// - /// An attribute class indicating to AutoRest which constructor to use for initialization. - /// - [AttributeUsage(AttributeTargets.Constructor)] - internal class InitializationConstructorAttribute : Attribute - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ManagedServiceIdentityTypeV3Converter.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ManagedServiceIdentityTypeV3Converter.cs deleted file mode 100644 index b33c186e19..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ManagedServiceIdentityTypeV3Converter.cs +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace Azure.ResourceManager.Models -{ - /// JsonConverter for managed service identity type v3. - internal class ManagedServiceIdentityTypeV3Converter : JsonConverter - { - internal const string SystemAssignedUserAssignedV3Value = "SystemAssigned,UserAssigned"; - - /// Serialize managed service identity type to v3 format. - /// The writer. - /// The ManagedServiceIdentityType model which is v4. - /// The options for JsonSerializer. - public override void Write(Utf8JsonWriter writer, ManagedServiceIdentityType model, JsonSerializerOptions options) - { - writer.WritePropertyName("type"); - if (model == ManagedServiceIdentityType.SystemAssignedUserAssigned) - { - writer.WriteStringValue(SystemAssignedUserAssignedV3Value); - } - else - { - writer.WriteStringValue(model.ToString()); - } - } - - /// Deserialize managed service identity type from v3 format. - /// The reader. - /// The type to convert - /// The options for JsonSerializer. - public override ManagedServiceIdentityType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using var document = JsonDocument.ParseValue(ref reader); - foreach (var property in document.RootElement.EnumerateObject()) - { - var typeValue = property.Value.GetString(); - if (typeValue.Equals(SystemAssignedUserAssignedV3Value, StringComparison.OrdinalIgnoreCase)) - { - return ManagedServiceIdentityType.SystemAssignedUserAssigned; - } - return new ManagedServiceIdentityType(typeValue); - } - return null; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/NextLinkOperationImplementation.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/NextLinkOperationImplementation.cs deleted file mode 100644 index d4dc0403e2..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/NextLinkOperationImplementation.cs +++ /dev/null @@ -1,701 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; - -namespace Azure.Core -{ - internal class NextLinkOperationImplementation : IOperation - { - internal const string NotSet = "NOT_SET"; - internal const string RehydrationTokenVersion = "1.0.0"; - private const string ApiVersionParam = "api-version"; - private static readonly string[] FailureStates = { "failed", "canceled" }; - private static readonly string[] SuccessStates = { "succeeded" }; - - private readonly HeaderSource _headerSource; - private readonly Uri _startRequestUri; - private readonly OperationFinalStateVia _finalStateVia; - private readonly HttpPipeline _pipeline; - private readonly string? _apiVersion; - - private string? _lastKnownLocation; - private string _nextRequestUri; - - // We can only get OperationId when - // - The operation is still in progress and nextRequestUri contains it - // - During rehydration, rehydrationToken.Id is the operation id - public string OperationId { get; private set; } = NotSet; - public RequestMethod RequestMethod { get; } - - public static IOperation Create( - HttpPipeline pipeline, - RequestMethod requestMethod, - Uri startRequestUri, - Response response, - OperationFinalStateVia finalStateVia, - bool skipApiVersionOverride = false, - string? apiVersionOverrideValue = null) - { - string? apiVersionStr = null; - if (apiVersionOverrideValue is not null) - { - apiVersionStr = apiVersionOverrideValue; - } - else - { - apiVersionStr = !skipApiVersionOverride && TryGetApiVersion(startRequestUri, out ReadOnlySpan apiVersion) ? apiVersion.ToString() : null; - } - var headerSource = GetHeaderSource(requestMethod, startRequestUri, response, apiVersionStr, out string nextRequestUri, out bool isNextRequestPolling); - - string? lastKnownLocation; - if (!response.Headers.TryGetValue("Location", out lastKnownLocation)) - { - lastKnownLocation = null; - } - - NextLinkOperationImplementation operation = new(pipeline, requestMethod, startRequestUri, nextRequestUri, headerSource, lastKnownLocation, finalStateVia, apiVersionStr, isNextRequestPolling: isNextRequestPolling); - - if (headerSource == HeaderSource.None && IsFinalState(response, headerSource, out var failureState, out _)) - { - return new CompletedOperation(failureState ?? GetOperationStateFromFinalResponse(requestMethod, response), operation); - } - - return operation; - } - - public static IOperation Create( - IOperationSource operationSource, - HttpPipeline pipeline, - RequestMethod requestMethod, - Uri startRequestUri, - Response response, - OperationFinalStateVia finalStateVia, - bool skipApiVersionOverride = false, - string? apiVersionOverrideValue = null) - { - var operation = Create(pipeline, requestMethod, startRequestUri, response, finalStateVia, skipApiVersionOverride, apiVersionOverrideValue); - return new OperationToOperationOfT(operationSource, operation); - } - - public static IOperation Create( - IOperationSource operationSource, - IOperation operation) - => new OperationToOperationOfT(operationSource, operation); - - public static IOperation Create( - HttpPipeline pipeline, - RehydrationToken rehydrationToken) - { - AssertNotNull(rehydrationToken, nameof(rehydrationToken)); - AssertNotNull(pipeline, nameof(pipeline)); - - // TODO: Once we remove NextLinkOperationImplementation from internal shared and make it internal to Azure.Core only in https://github.com/Azure/azure-sdk-for-net/issues/43260 - // We can access the internal members from RehydrationToken directly - var data = ModelReaderWriter.Write(rehydrationToken!, ModelReaderWriterOptions.Json, AzureCoreContext.Default); - using var document = JsonDocument.Parse(data); - var lroDetails = document.RootElement; - - // We are sure that the following properties exists in the serialized rehydrationToken - var initialUri = lroDetails.GetProperty("initialUri").GetString(); - if (!Uri.TryCreate(initialUri, UriKind.Absolute, out var startRequestUri)) - { - throw new ArgumentException($"\"initialUri\" property on \"rehydrationToken\" is an invalid Uri", nameof(rehydrationToken)); - } - - // We are sure that the following properties(apart from nullable lastKnownLocation) are not null as they are required in the rehydrationToken - string nextRequestUri = lroDetails.GetProperty("nextRequestUri").GetString()!; - string requestMethodStr = lroDetails.GetProperty("requestMethod").GetString()!; - RequestMethod requestMethod = new RequestMethod(requestMethodStr)!; - string? lastKnownLocation = lroDetails.GetProperty("lastKnownLocation").GetString(); - - string finalStateViaStr = lroDetails.GetProperty("finalStateVia").GetString()!; - OperationFinalStateVia finalStateVia; - if (Enum.IsDefined(typeof(OperationFinalStateVia), finalStateViaStr)) - { - finalStateVia = (OperationFinalStateVia)Enum.Parse(typeof(OperationFinalStateVia), finalStateViaStr); - } - else - { - finalStateVia = OperationFinalStateVia.Location; - } - - string headerSourceStr = lroDetails.GetProperty("headerSource").GetString()!; - HeaderSource headerSource; - if (Enum.IsDefined(typeof(HeaderSource), headerSourceStr)) - { - headerSource = (HeaderSource)Enum.Parse(typeof(HeaderSource), headerSourceStr); - } - else - { - headerSource = HeaderSource.None; - } - - return new NextLinkOperationImplementation(pipeline, requestMethod, startRequestUri, nextRequestUri, headerSource, lastKnownLocation, finalStateVia, null, rehydrationToken.Id); - } - - private NextLinkOperationImplementation( - HttpPipeline pipeline, - RequestMethod requestMethod, - Uri startRequestUri, - string nextRequestUri, - HeaderSource headerSource, - string? lastKnownLocation, - OperationFinalStateVia finalStateVia, - string? apiVersion, - string? operationId = null, - bool isNextRequestPolling = false) - { - AssertNotNull(pipeline, nameof(pipeline)); - AssertNotNull(requestMethod, nameof(requestMethod)); - AssertNotNull(startRequestUri, nameof(startRequestUri)); - AssertNotNull(nextRequestUri, nameof(nextRequestUri)); - AssertNotNull(headerSource, nameof(headerSource)); - AssertNotNull(finalStateVia, nameof(finalStateVia)); - - RequestMethod = requestMethod; - _headerSource = headerSource; - _startRequestUri = startRequestUri; - _nextRequestUri = nextRequestUri; - _lastKnownLocation = lastKnownLocation; - _finalStateVia = finalStateVia; - _pipeline = pipeline; - _apiVersion = apiVersion; - if (operationId is not null) - { - OperationId = operationId; - } - else if (isNextRequestPolling) - { - OperationId = ParseOperationId(startRequestUri, nextRequestUri); - } - } - - private static string ParseOperationId(Uri startRequestUri, string nextRequestUri) - { - if (Uri.TryCreate(nextRequestUri, UriKind.Absolute, out var nextLink) && nextLink.Scheme != "file") - { - return nextLink.Segments.Last(); - } - else - { - return new Uri(startRequestUri, nextRequestUri).Segments.Last(); - } - } - - public RehydrationToken GetRehydrationToken() - => GetRehydrationToken(RequestMethod, _startRequestUri, _nextRequestUri, _headerSource.ToString(), _lastKnownLocation, _finalStateVia.ToString(), OperationId); - - public static RehydrationToken GetRehydrationToken( - RequestMethod requestMethod, - Uri startRequestUri, - Response response, - OperationFinalStateVia finalStateVia) - { - AssertNotNull(requestMethod, nameof(requestMethod)); - AssertNotNull(startRequestUri, nameof(startRequestUri)); - AssertNotNull(response, nameof(response)); - AssertNotNull(finalStateVia, nameof(finalStateVia)); - - var headerSource = GetHeaderSource(requestMethod, startRequestUri, response, null, out string nextRequestUri, out bool isNextRequestPolling); - string? lastKnownLocation; - if (!response.Headers.TryGetValue("Location", out lastKnownLocation)) - { - lastKnownLocation = null; - } - return GetRehydrationToken(requestMethod, startRequestUri, nextRequestUri, headerSource.ToString(), lastKnownLocation, finalStateVia.ToString(), isNextRequestPolling ? ParseOperationId(startRequestUri, nextRequestUri) : null); - } - - public static RehydrationToken GetRehydrationToken( - RequestMethod requestMethod, - Uri startRequestUri, - string nextRequestUri, - string headerSource, - string? lastKnownLocation, - string finalStateVia, - string? operationId = null) - { - // TODO: Once we remove NextLinkOperationImplementation from internal shared and make it internal to Azure.Core only in https://github.com/Azure/azure-sdk-for-net/issues/43260 - // We can access the internal members from RehydrationToken directly - var json = $$""" - {"version":"{{RehydrationTokenVersion}}","id":{{ConstructStringValue(operationId)}},"requestMethod":"{{requestMethod}}","initialUri":"{{startRequestUri.AbsoluteUri}}","nextRequestUri":"{{nextRequestUri}}","headerSource":"{{headerSource}}","finalStateVia":"{{finalStateVia}}","lastKnownLocation":{{ConstructStringValue(lastKnownLocation)}}} - """; - var data = new BinaryData(json); - return ModelReaderWriter.Read(data, ModelReaderWriterOptions.Json, AzureCoreContext.Default); - } - - private static string? ConstructStringValue(string? value) => value is null ? "null" : $"\"{value}\""; - - public async ValueTask UpdateStateAsync(bool async, CancellationToken cancellationToken) - { - Response response = async - ? await GetResponseAsync(_nextRequestUri, cancellationToken).ConfigureAwait(false) - : GetResponse(_nextRequestUri, cancellationToken); - - var hasCompleted = IsFinalState(response, _headerSource, out var failureState, out var resourceLocation); - if (failureState != null) - { - return failureState.Value; - } - - if (hasCompleted) - { - string? finalUri = GetFinalUri(resourceLocation); - Response finalResponse; - if (finalUri != null) - { - finalResponse = async - ? await GetResponseAsync(finalUri, cancellationToken).ConfigureAwait(false) - : GetResponse(finalUri, cancellationToken); - } - else - { - finalResponse = response; - } - return GetOperationStateFromFinalResponse(RequestMethod, finalResponse); - } - - UpdateNextRequestUri(response.Headers); - return OperationState.Pending(response); - } - - private static OperationState GetOperationStateFromFinalResponse(RequestMethod requestMethod, Response response) - { - switch (response.Status) - { - case 200: - case 201 when requestMethod == RequestMethod.Put: - case 204 when requestMethod != RequestMethod.Put && requestMethod != RequestMethod.Patch: - return OperationState.Success(response); - default: - return OperationState.Failure(response); - } - } - - private void UpdateNextRequestUri(ResponseHeaders headers) - { - var hasLocation = headers.TryGetValue("Location", out string? location); - if (hasLocation) - { - _lastKnownLocation = location; - } - - switch (_headerSource) - { - case HeaderSource.OperationLocation when headers.TryGetValue("Operation-Location", out string? operationLocation): - _nextRequestUri = AppendOrReplaceApiVersion(operationLocation, _apiVersion); - OperationId = ParseOperationId(_startRequestUri, _nextRequestUri); - return; - case HeaderSource.AzureAsyncOperation when headers.TryGetValue("Azure-AsyncOperation", out string? azureAsyncOperation): - _nextRequestUri = AppendOrReplaceApiVersion(azureAsyncOperation, _apiVersion); - OperationId = ParseOperationId(_startRequestUri, _nextRequestUri); - return; - case HeaderSource.Location when hasLocation: - _nextRequestUri = AppendOrReplaceApiVersion(location!, _apiVersion); - OperationId = ParseOperationId(_startRequestUri, _nextRequestUri); - return; - } - } - - internal static string AppendOrReplaceApiVersion(string uri, string? apiVersion) - { - if (!string.IsNullOrEmpty(apiVersion)) - { - var uriSpan = uri.AsSpan(); - var apiVersionParamSpan = ApiVersionParam.AsSpan(); - var apiVersionIndex = uriSpan.IndexOf(apiVersionParamSpan); - if (apiVersionIndex == -1) - { - var concatSymbol = uriSpan.IndexOf('?') > -1 ? "&" : "?"; - return $"{uri}{concatSymbol}api-version={apiVersion}"; - } - else - { - var lengthToEndOfApiVersionParam = apiVersionIndex + ApiVersionParam.Length; - ReadOnlySpan remaining = uriSpan.Slice(lengthToEndOfApiVersionParam); - bool apiVersionHasEqualSign = false; - if (remaining.IndexOf('=') == 0) - { - remaining = remaining.Slice(1); - lengthToEndOfApiVersionParam += 1; - apiVersionHasEqualSign = true; - } - var indexOfFirstSignAfterApiVersion = remaining.IndexOf('&'); - ReadOnlySpan uriBeforeApiVersion = uriSpan.Slice(0, lengthToEndOfApiVersionParam); - if (indexOfFirstSignAfterApiVersion == -1) - { - return string.Concat(uriBeforeApiVersion.ToString(), apiVersionHasEqualSign ? string.Empty : "=", apiVersion); - } - else - { - ReadOnlySpan uriAfterApiVersion = uriSpan.Slice(indexOfFirstSignAfterApiVersion + lengthToEndOfApiVersionParam); - return string.Concat(uriBeforeApiVersion.ToString(), apiVersionHasEqualSign ? string.Empty : "=", apiVersion, uriAfterApiVersion.ToString()); - } - } - } - return uri; - } - - internal static bool TryGetApiVersion(Uri startRequestUri, out ReadOnlySpan apiVersion) - { - apiVersion = default; - ReadOnlySpan uriSpan = startRequestUri.Query.AsSpan(); - int startIndex = uriSpan.IndexOf(ApiVersionParam.AsSpan()); - if (startIndex == -1) - { - return false; - } - startIndex += ApiVersionParam.Length; - ReadOnlySpan remaining = uriSpan.Slice(startIndex); - if (remaining.IndexOf('=') == 0) - { - remaining = remaining.Slice(1); - startIndex += 1; - } - else - { - return false; - } - int endIndex = remaining.IndexOf('&'); - int length = endIndex == -1 ? uriSpan.Length - startIndex : endIndex; - apiVersion = uriSpan.Slice(startIndex, length); - return true; - } - - /// - /// This function is used to get the final request uri after the lro has completed. - /// - private string? GetFinalUri(string? resourceLocation) - { - // Set final uri as null if the response for initial request doesn't contain header "Operation-Location" or "Azure-AsyncOperation". - if (_headerSource is not (HeaderSource.OperationLocation or HeaderSource.AzureAsyncOperation)) - { - return null; - } - - // Set final uri as null if initial request is a delete method. - if (RequestMethod == RequestMethod.Delete) - { - return null; - } - - // Handle final-state-via options: https://github.com/Azure/autorest/blob/main/docs/extensions/readme.md#x-ms-long-running-operation-options - switch (_finalStateVia) - { - case OperationFinalStateVia.LocationOverride when !string.IsNullOrEmpty(_lastKnownLocation): - return _lastKnownLocation; - case OperationFinalStateVia.OperationLocation or OperationFinalStateVia.AzureAsyncOperation when RequestMethod == RequestMethod.Post: - return null; - case OperationFinalStateVia.OriginalUri: - return _startRequestUri.AbsoluteUri; - } - - // If response body contains resourceLocation, use it: https://github.com/microsoft/api-guidelines/blob/vNext/Guidelines.md#target-resource-location - if (resourceLocation != null) - { - return resourceLocation; - } - - // If initial request is PUT or PATCH, return initial request Uri - if (RequestMethod == RequestMethod.Put || RequestMethod == RequestMethod.Patch) - { - return _startRequestUri.AbsoluteUri; - } - - // If response for initial request contains header "Location", return last known location - if (!string.IsNullOrEmpty(_lastKnownLocation)) - { - return _lastKnownLocation; - } - - return null; - } - - private Response GetResponse(string uri, CancellationToken cancellationToken) - { - using HttpMessage message = CreateRequest(uri); - _pipeline.Send(message, cancellationToken); - - // If we are doing final get for a delete LRO with 404, just return empty response with 204 - if (message.Response.Status == 404 && RequestMethod == RequestMethod.Delete) - { - return new EmptyResponse(HttpStatusCode.NoContent, message.Response.ClientRequestId); - } - return message.Response; - } - - private async ValueTask GetResponseAsync(string uri, CancellationToken cancellationToken) - { - using HttpMessage message = CreateRequest(uri); - await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); - - // If we are doing final get for a delete LRO with 404, just return empty response with 204 - if (message.Response.Status == 404 && RequestMethod == RequestMethod.Delete) - { - return new EmptyResponse(HttpStatusCode.NoContent, message.Response.ClientRequestId); - } - return message.Response; - } - - /// - /// This is only used for final get of the delete LRO, we just want to return an empty response with 204 to the user for this case. - /// - private sealed class EmptyResponse : Response - { - public EmptyResponse(HttpStatusCode status, string clientRequestId) - { - Status = (int)status; - ReasonPhrase = status.ToString(); - ClientRequestId = clientRequestId; - } - - public override int Status { get; } - - public override string ReasonPhrase { get; } - - public override Stream? ContentStream { get => null; set => throw new InvalidOperationException("Should not set ContentStream for an empty response."); } - public override string ClientRequestId { get; set; } - - public override void Dispose() - { - } - - /// -#if HAS_INTERNALS_VISIBLE_CORE - internal -#endif - protected override bool ContainsHeader(string name) => false; - - /// -#if HAS_INTERNALS_VISIBLE_CORE - internal -#endif - protected override IEnumerable EnumerateHeaders() => Array.Empty(); - - /// -#if HAS_INTERNALS_VISIBLE_CORE - internal -#endif - protected override bool TryGetHeader(string name, out string value) - { - value = string.Empty; - return false; - } - - /// -#if HAS_INTERNALS_VISIBLE_CORE - internal -#endif - protected override bool TryGetHeaderValues(string name, out IEnumerable values) - { - values = Array.Empty(); - return false; - } - } - - private HttpMessage CreateRequest(string uri) - { - HttpMessage message = _pipeline.CreateMessage(); - Request request = message.Request; - request.Method = RequestMethod.Get; - - if (Uri.TryCreate(uri, UriKind.Absolute, out var nextLink) && nextLink.Scheme != "file") - { - request.Uri.Reset(nextLink); - } - else - { - request.Uri.Reset(new Uri(_startRequestUri, uri)); - } - - return message; - } - - private static bool IsFinalState(Response response, HeaderSource headerSource, out OperationState? failureState, out string? resourceLocation) - { - failureState = null; - resourceLocation = null; - - if (headerSource == HeaderSource.Location) - { - return response.Status != 202; - } - - if (response.Status is >= 200 and <= 204) - { - if (response.ContentStream is { Length: > 0 }) - { - try - { - using JsonDocument document = JsonDocument.Parse(response.ContentStream); - var root = document.RootElement; - switch (headerSource) - { - case HeaderSource.None when root.TryGetProperty("properties", out var properties) && properties.TryGetProperty("provisioningState", out JsonElement property): - case HeaderSource.OperationLocation when root.TryGetProperty("status", out property): - case HeaderSource.AzureAsyncOperation when root.TryGetProperty("status", out property): - var state = GetRequiredString(property).ToLowerInvariant(); - if (FailureStates.Contains(state)) - { - failureState = OperationState.Failure(response); - return true; - } - else if (!SuccessStates.Contains(state)) - { - return false; - } - else - { - if (headerSource is HeaderSource.OperationLocation or HeaderSource.AzureAsyncOperation && root.TryGetProperty("resourceLocation", out var resourceLocationProperty)) - { - resourceLocation = resourceLocationProperty.GetString(); - } - return true; - } - } - } - finally - { - // It is required to reset the position of the content after reading as this response may be used for deserialization. - response.ContentStream.Position = 0; - } - } - - // If headerSource is None and provisioningState was not found, it defaults to Succeeded. - if (headerSource == HeaderSource.None) - { - return true; - } - } - - failureState = OperationState.Failure(response); - return true; - } - - private static string GetRequiredString(in JsonElement element) - { - var value = element.GetString(); - if (value == null) - throw new InvalidOperationException($"The requested operation requires an element of type 'String', but the target element has type '{element.ValueKind}'."); - - return value; - } - - private static bool ShouldIgnoreHeader(RequestMethod method, Response response) - => method.Method == RequestMethod.Patch.Method && response.Status == 200; - - // Since this method is static, we can't manipulate the instance property OperationId of the class. We need to return isRequestPolling to update the OperationId after creaing the instance. - private static HeaderSource GetHeaderSource(RequestMethod requestMethod, Uri requestUri, Response response, string? apiVersion, out string nextRequestUri, out bool isNextRequestPolling) - { - isNextRequestPolling = false; - if (ShouldIgnoreHeader(requestMethod, response)) - { - nextRequestUri = requestUri.AbsoluteUri; - return HeaderSource.None; - } - - var headers = response.Headers; - if (headers.TryGetValue("Operation-Location", out var operationLocationUri)) - { - nextRequestUri = AppendOrReplaceApiVersion(operationLocationUri, apiVersion); - isNextRequestPolling = true; - return HeaderSource.OperationLocation; - } - - if (headers.TryGetValue("Azure-AsyncOperation", out var azureAsyncOperationUri)) - { - nextRequestUri = AppendOrReplaceApiVersion(azureAsyncOperationUri, apiVersion); - isNextRequestPolling = true; - return HeaderSource.AzureAsyncOperation; - } - - if (headers.TryGetValue("Location", out var locationUri)) - { - nextRequestUri = AppendOrReplaceApiVersion(locationUri, apiVersion); - isNextRequestPolling = true; - return HeaderSource.Location; - } - - nextRequestUri = requestUri.AbsoluteUri; - return HeaderSource.None; - } - - private static void AssertNotNull(T value, string name) - { - if (value is null) - { - throw new ArgumentNullException(name); - } - } - - private enum HeaderSource - { - None, - OperationLocation, - AzureAsyncOperation, - Location - } - - private class CompletedOperation : IOperation - { - private readonly OperationState _operationState; - - private readonly NextLinkOperationImplementation _operation; - - public CompletedOperation(OperationState operationState, NextLinkOperationImplementation operation) - { - _operationState = operationState; - _operation = operation; - } - - public ValueTask UpdateStateAsync(bool async, CancellationToken cancellationToken) => new(_operationState); - - public RehydrationToken GetRehydrationToken() => _operation.GetRehydrationToken(); - } - - private sealed class OperationToOperationOfT : IOperation - { - private readonly IOperationSource _operationSource; - private readonly IOperation _operation; - - public OperationToOperationOfT(IOperationSource operationSource, IOperation operation) - { - _operationSource = operationSource; - _operation = operation; - } - - public async ValueTask> UpdateStateAsync(bool async, CancellationToken cancellationToken) - { - var state = await _operation.UpdateStateAsync(async, cancellationToken).ConfigureAwait(false); - if (state.HasSucceeded) - { - var result = async - ? await _operationSource.CreateResultAsync(state.RawResponse, cancellationToken).ConfigureAwait(false) - : _operationSource.CreateResult(state.RawResponse, cancellationToken); - - return OperationState.Success(state.RawResponse, result); - } - - if (state.HasCompleted) - { - return OperationState.Failure(state.RawResponse, state.OperationFailedException); - } - - return OperationState.Pending(state.RawResponse); - } - - public RehydrationToken GetRehydrationToken() => _operation.GetRehydrationToken(); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/NoValueResponseOfT.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/NoValueResponseOfT.cs deleted file mode 100644 index 95fa1e2573..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/NoValueResponseOfT.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -namespace Azure -{ -#pragma warning disable SA1649 // File name should match first type name - internal sealed class NoValueResponse : NullableResponse -#pragma warning restore SA1649 // File name should match first type name - { - private readonly Response _response; - - public NoValueResponse(Response response) - { - _response = response ?? throw new ArgumentNullException(nameof(response)); - } - - /// - public override bool HasValue => false; - - public override T Value - { - get - { - throw new InvalidOperationException(GetStatusMessage()); - } - } - - public override Response GetRawResponse() => _response; - - public override string ToString() - { - return GetStatusMessage(); - } - - internal string GetStatusMessage() => $"Status: {GetRawResponse().Status}, Service returned no content"; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationFinalStateVia.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationFinalStateVia.cs deleted file mode 100644 index 8ad2396db9..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationFinalStateVia.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -namespace Azure.Core -{ - internal enum OperationFinalStateVia - { - AzureAsyncOperation, - Location, - OriginalUri, - OperationLocation, - LocationOverride, - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationInternal.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationInternal.cs deleted file mode 100644 index 2435465459..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationInternal.cs +++ /dev/null @@ -1,263 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; - -#nullable enable - -namespace Azure.Core -{ - /// - /// A helper class used to build long-running operation instances. In order to use this helper: - /// - /// Make sure your LRO implements the interface. - /// Add a private field to your LRO, and instantiate it during construction. - /// Delegate method calls to the implementations. - /// - /// Supported members: - /// - /// - /// - /// - /// - /// , used for - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - internal class OperationInternal : OperationInternalBase - { - // To minimize code duplication and avoid introduction of another type, - // OperationInternal delegates implementation to the OperationInternal. - // VoidValue is a private empty struct which only purpose is to be used as generic parameter. - private readonly OperationInternal _internalOperation; - - /// - /// Initializes a new instance of the class in a final successful state. - /// - /// The final value of . - public static OperationInternal Succeeded(Response rawResponse) => new(OperationState.Success(rawResponse)); - - /// - /// Initializes a new instance of the class in a final failed state. - /// - /// The final value of . - /// The exception that will be thrown by UpdateStatusAsync. - public static OperationInternal Failed(Response rawResponse, RequestFailedException operationFailedException) => new(OperationState.Failure(rawResponse, operationFailedException)); - - /// - /// Initializes a new instance of the class. - /// - /// The long-running operation making use of this class. Passing "this" is expected. - /// Used for diagnostic scope and exception creation. This is expected to be the instance created during the construction of your main client. - /// - /// The initial value of . Usually, long-running operation objects can be instantiated in two ways: - /// - /// - /// When calling a client's "Start<OperationName>" method, a service call is made to start the operation, and an instance is returned. - /// In this case, the response received from this service call can be passed here. - /// - /// - /// When a user instantiates an directly using a public constructor, there's no previous service call. In this case, passing null is expected. - /// - /// - /// - /// - /// The type name of the long-running operation making use of this class. Used when creating diagnostic scopes. If left null, the type name will be inferred based on the - /// parameter . - /// - /// The attributes to use during diagnostic scope creation. - /// The delay strategy to use. Default is . - public OperationInternal(IOperation operation, - ClientDiagnostics clientDiagnostics, - Response rawResponse, - string? operationTypeName = null, - IEnumerable>? scopeAttributes = null, - DelayStrategy? fallbackStrategy = null) - : base(clientDiagnostics, operationTypeName ?? operation.GetType().Name, scopeAttributes, fallbackStrategy) - { - _internalOperation = new OperationInternal(new OperationToOperationOfTProxy(operation), clientDiagnostics, rawResponse, operationTypeName ?? operation.GetType().Name, scopeAttributes, fallbackStrategy); - } - - internal OperationInternal(OperationState finalState) - : base(finalState.RawResponse) - { - _internalOperation = finalState.HasSucceeded - ? OperationInternal.Succeeded(finalState.RawResponse, default) - : OperationInternal.Failed(finalState.RawResponse, finalState.OperationFailedException!); - } - - public override Response RawResponse => _internalOperation.RawResponse; - - public override bool HasCompleted => _internalOperation.HasCompleted; - - protected override async ValueTask UpdateStatusAsync(bool async, CancellationToken cancellationToken) => - async ? await _internalOperation.UpdateStatusAsync(cancellationToken).ConfigureAwait(false) : _internalOperation.UpdateStatus(cancellationToken); - - // Wrapper type that converts OperationState to OperationState and can be passed to `OperationInternal` constructor. - private class OperationToOperationOfTProxy : IOperation - { - private readonly IOperation _operation; - - public OperationToOperationOfTProxy(IOperation operation) - { - _operation = operation; - } - - public RehydrationToken GetRehydrationToken() => _operation.GetRehydrationToken(); - - public async ValueTask> UpdateStateAsync(bool async, CancellationToken cancellationToken) - { - var state = await _operation.UpdateStateAsync(async, cancellationToken).ConfigureAwait(false); - if (!state.HasCompleted) - { - return OperationState.Pending(state.RawResponse); - } - - if (state.HasSucceeded) - { - return OperationState.Success(state.RawResponse, new VoidValue()); - } - - return OperationState.Failure(state.RawResponse, state.OperationFailedException); - } - } - } - - /// - /// An interface used by for making service calls and updating state. It's expected that - /// your long-running operation classes implement this interface. - /// - internal interface IOperation - { - /// - /// Calls the service and updates the state of the long-running operation. Properties directly handled by the - /// class, such as - /// don't need to be updated. Operation-specific properties, such as "CreateOn" or "LastModified", - /// must be manually updated by the operation implementing this method. - /// Usage example: - /// - /// async ValueTask<OperationState> IOperation.UpdateStateAsync(bool async, CancellationToken cancellationToken)
- /// {
- /// Response<R> response = async ? <async service call> : <sync service call>;
- /// if (<operation succeeded>) return OperationState.Success(response.GetRawResponse(), <parse response>);
- /// if (<operation failed>) return OperationState.Failure(response.GetRawResponse());
- /// return OperationState.Pending(response.GetRawResponse());
- /// } - ///
- ///
- ///
- /// true if the call should be executed asynchronously. Otherwise, false. - /// A controlling the request lifetime. - /// - /// A structure indicating the current operation state. The structure must be instantiated by one of - /// its static methods: - /// - /// Use when the operation has completed successfully. - /// Use when the operation has completed with failures. - /// Use when the operation has not completed yet. - /// - /// - ValueTask UpdateStateAsync(bool async, CancellationToken cancellationToken); - - /// - /// Get a token that can be used to rehydrate the operation. - /// - RehydrationToken GetRehydrationToken(); - } - - /// - /// A helper structure passed to to indicate the current operation state. This structure must be - /// instantiated by one of its static methods, depending on the operation state: - /// - /// Use when the operation has completed successfully. - /// Use when the operation has completed with failures. - /// Use when the operation has not completed yet. - /// - /// - internal readonly struct OperationState - { - private OperationState(Response rawResponse, bool hasCompleted, bool hasSucceeded, RequestFailedException? operationFailedException) - { - RawResponse = rawResponse; - HasCompleted = hasCompleted; - HasSucceeded = hasSucceeded; - OperationFailedException = operationFailedException; - } - - public Response RawResponse { get; } - - public bool HasCompleted { get; } - - public bool HasSucceeded { get; } - - public RequestFailedException? OperationFailedException { get; } - - /// - /// Instantiates an indicating the operation has completed successfully. - /// - /// The HTTP response obtained during the status update. - /// A new instance. - /// Thrown if is null. - public static OperationState Success(Response rawResponse) - { - if (rawResponse is null) - { - throw new ArgumentNullException(nameof(rawResponse)); - } - - return new OperationState(rawResponse, true, true, default); - } - - /// - /// Instantiates an indicating the operation has completed with failures. - /// - /// The HTTP response obtained during the status update. - /// - /// The exception to throw from UpdateStatus because of the operation failure. If left null, - /// a default exception is created based on the parameter. - /// - /// A new instance. - /// Thrown if is null. - public static OperationState Failure(Response rawResponse, RequestFailedException? operationFailedException = null) - { - if (rawResponse is null) - { - throw new ArgumentNullException(nameof(rawResponse)); - } - - return new OperationState(rawResponse, true, false, operationFailedException); - } - - /// - /// Instantiates an indicating the operation has not completed yet. - /// - /// The HTTP response obtained during the status update. - /// A new instance. - /// Thrown if is null. - public static OperationState Pending(Response rawResponse) - { - if (rawResponse is null) - { - throw new ArgumentNullException(nameof(rawResponse)); - } - - return new OperationState(rawResponse, false, default, default); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationInternalBase.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationInternalBase.cs deleted file mode 100644 index dad6480c22..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationInternalBase.cs +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; - -namespace Azure.Core -{ - internal abstract class OperationInternalBase - { - private readonly ClientDiagnostics _diagnostics; - private readonly IReadOnlyDictionary? _scopeAttributes; - private readonly DelayStrategy? _fallbackStrategy; - private readonly AsyncLockWithValue _responseLock; - - private readonly string _waitForCompletionResponseScopeName; - protected readonly string _updateStatusScopeName; - protected readonly string _waitForCompletionScopeName; - - protected OperationInternalBase(Response rawResponse) - { - _diagnostics = new ClientDiagnostics(ClientOptions.Default); - _updateStatusScopeName = string.Empty; - _waitForCompletionResponseScopeName = string.Empty; - _waitForCompletionScopeName = string.Empty; - _scopeAttributes = default; - _fallbackStrategy = default; - _responseLock = new AsyncLockWithValue(rawResponse); - } - - protected OperationInternalBase(ClientDiagnostics clientDiagnostics, string operationTypeName, IEnumerable>? scopeAttributes = null, DelayStrategy? fallbackStrategy = null) - { - _diagnostics = clientDiagnostics; - _updateStatusScopeName = $"{operationTypeName}.{nameof(UpdateStatus)}"; - _waitForCompletionResponseScopeName = $"{operationTypeName}.{nameof(WaitForCompletionResponse)}"; - _waitForCompletionScopeName = $"{operationTypeName}.WaitForCompletion"; - _scopeAttributes = scopeAttributes?.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); - _fallbackStrategy = fallbackStrategy; - _responseLock = new AsyncLockWithValue(); - } - - /// - /// The last HTTP response received from the server. Its update already handled in calls to "UpdateStatus" and - /// "WaitForCompletionAsync", but custom methods not supported by this class, such as "CancelOperation", - /// must update it as well. - /// Usage example: - /// - /// public Response GetRawResponse() => _operationInternal.RawResponse; - /// - /// - /// - public abstract Response RawResponse { get; } - - /// - /// Returns true if the long-running operation has completed. - /// Usage example: - /// - /// public bool HasCompleted => _operationInternal.HasCompleted; - /// - /// - /// - public abstract bool HasCompleted { get; } - - /// - /// Calls the server to get the latest status of the long-running operation, handling diagnostic scope creation for distributed - /// tracing. The default scope name can be changed with the "operationTypeName" parameter passed to the constructor. - /// Usage example: - /// - /// public async ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken) => - /// await _operationInternal.UpdateStatusAsync(cancellationToken).ConfigureAwait(false); - /// - /// - /// - /// A controlling the request lifetime. - /// The HTTP response received from the server. - /// - /// After a successful run, this method will update and might update . - /// - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public async ValueTask UpdateStatusAsync(CancellationToken cancellationToken) => - await UpdateStatusAsync(async: true, cancellationToken).ConfigureAwait(false); - - /// - /// Calls the server to get the latest status of the long-running operation, handling diagnostic scope creation for distributed - /// tracing. The default scope name can be changed with the "operationTypeName" parameter passed to the constructor. - /// Usage example: - /// - /// public Response UpdateStatus(CancellationToken cancellationToken) => _operationInternal.UpdateStatus(cancellationToken); - /// - /// - /// - /// A controlling the request lifetime. - /// The HTTP response received from the server. - /// - /// After a successful run, this method will update and might update . - /// - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public Response UpdateStatus(CancellationToken cancellationToken) => - UpdateStatusAsync(async: false, cancellationToken).EnsureCompleted(); - - /// - /// Periodically calls until the long-running operation completes. - /// After each service call, a retry-after header may be returned to communicate that there is no reason to poll - /// for status change until the specified time has passed. The maximum of the retry after value and the fallback strategy - /// is then used as the wait interval. - /// Headers supported are: "Retry-After", "retry-after-ms", and "x-ms-retry-after-ms", - /// Usage example: - /// - /// public async ValueTask<Response<T>> WaitForCompletionAsync(CancellationToken cancellationToken) => - /// await _operationInternal.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - /// - /// - /// - /// A controlling the request lifetime. - /// The last HTTP response received from the server, including the final result of the long-running operation. - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public async ValueTask WaitForCompletionResponseAsync(CancellationToken cancellationToken) - => await WaitForCompletionResponseAsync(async: true, null, _waitForCompletionResponseScopeName, cancellationToken).ConfigureAwait(false); - - /// - /// Periodically calls until the long-running operation completes. The interval - /// between calls is defined by the parameter , but it can change based on information returned - /// from the server. After each service call, a retry-after header may be returned to communicate that there is no reason to poll - /// for status change until the specified time has passed. In this case, the maximum value between the - /// parameter and the retry-after header is chosen as the wait interval. Headers supported are: "Retry-After", "retry-after-ms", - /// and "x-ms-retry-after-ms". - /// Usage example: - /// - /// public async ValueTask<Response<T>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) => - /// await _operationInternal.WaitForCompletionAsync(pollingInterval, cancellationToken).ConfigureAwait(false); - /// - /// - /// - /// The interval between status requests to the server. - /// A controlling the request lifetime. - /// The last HTTP response received from the server, including the final result of the long-running operation. - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public async ValueTask WaitForCompletionResponseAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) - => await WaitForCompletionResponseAsync(async: true, pollingInterval, _waitForCompletionResponseScopeName, cancellationToken).ConfigureAwait(false); - - /// - /// Periodically calls until the long-running operation completes. - /// After each service call, a retry-after header may be returned to communicate that there is no reason to poll - /// for status change until the specified time has passed. The maximum of the retry after value and the fallback strategy - /// is then used as the wait interval. - /// Headers supported are: "Retry-After", "retry-after-ms", and "x-ms-retry-after-ms", - /// and "x-ms-retry-after-ms". - /// Usage example: - /// - /// public async ValueTask<Response<T>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) => - /// await _operationInternal.WaitForCompletionAsync(pollingInterval, cancellationToken).ConfigureAwait(false); - /// - /// - /// - /// A controlling the request lifetime. - /// The last HTTP response received from the server, including the final result of the long-running operation. - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public Response WaitForCompletionResponse(CancellationToken cancellationToken) - => WaitForCompletionResponseAsync(async: false, null, _waitForCompletionResponseScopeName, cancellationToken).EnsureCompleted(); - - /// - /// Periodically calls until the long-running operation completes. The interval - /// between calls is defined by the parameter , but it can change based on information returned - /// from the server. After each service call, a retry-after header may be returned to communicate that there is no reason to poll - /// for status change until the specified time has passed. In this case, the maximum value between the - /// parameter and the retry-after header is chosen as the wait interval. Headers supported are: "Retry-After", "retry-after-ms", - /// and "x-ms-retry-after-ms". - /// Usage example: - /// - /// public async ValueTask<Response<T>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) => - /// await _operationInternal.WaitForCompletionAsync(pollingInterval, cancellationToken).ConfigureAwait(false); - /// - /// - /// - /// The interval between status requests to the server. - /// A controlling the request lifetime. - /// The last HTTP response received from the server, including the final result of the long-running operation. - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public Response WaitForCompletionResponse(TimeSpan pollingInterval, CancellationToken cancellationToken) - => WaitForCompletionResponseAsync(async: false, pollingInterval, _waitForCompletionResponseScopeName, cancellationToken).EnsureCompleted(); - - protected async ValueTask WaitForCompletionResponseAsync(bool async, TimeSpan? pollingInterval, string scopeName, CancellationToken cancellationToken) - { - // If _responseLock has the value, lockOrValue will contain that value, and no lock is acquired. - // If _responseLock doesn't have the value, GetLockOrValueAsync will acquire the lock that will be released when lockOrValue is disposed - using var lockOrValue = await _responseLock.GetLockOrValueAsync(async, cancellationToken).ConfigureAwait(false); - if (lockOrValue.HasValue) - { - return lockOrValue.Value; - } - - using var scope = CreateScope(scopeName); - try - { - var poller = new OperationPoller(_fallbackStrategy); - var response = async - ? await poller.WaitForCompletionResponseAsync(this, pollingInterval, cancellationToken).ConfigureAwait(false) - : poller.WaitForCompletionResponse(this, pollingInterval, cancellationToken); - - lockOrValue.SetValue(response); - return response; - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - protected abstract ValueTask UpdateStatusAsync(bool async, CancellationToken cancellationToken); - - protected DiagnosticScope CreateScope(string scopeName) - { - DiagnosticScope scope = _diagnostics.CreateScope(scopeName); - - if (_scopeAttributes != null) - { - foreach (KeyValuePair attribute in _scopeAttributes) - { - scope.AddAttribute(attribute.Key, attribute.Value); - } - } - - scope.Start(); - return scope; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationInternalOfT.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationInternalOfT.cs deleted file mode 100644 index c1adc58603..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationInternalOfT.cs +++ /dev/null @@ -1,431 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; - -namespace Azure.Core -{ - /// - /// A helper class used to build long-running operation instances. In order to use this helper: - /// - /// Make sure your LRO implements the interface. - /// Add a private field to your LRO, and instantiate it during construction. - /// Delegate method calls to the implementations. - /// - /// Supported members: - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// , used for - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// The final result of the long-running operation. Must match the type used in . -#pragma warning disable SA1649 // File name should match first type name - internal class OperationInternal : OperationInternalBase -#pragma warning restore SA1649 - { - private readonly IOperation _operation; - private readonly AsyncLockWithValue> _stateLock; - private Response _rawResponse; - - /// - /// Initializes a new instance of the class in a final successful state. - /// - /// The final value of . - /// The final result of the long-running operation. - public static OperationInternal Succeeded(Response rawResponse, T value) => new(OperationState.Success(rawResponse, value)); - - /// - /// Initializes a new instance of the class in a final failed state. - /// - /// The final value of . - /// The exception that will be thrown by UpdateStatusAsync. - public static OperationInternal Failed(Response rawResponse, RequestFailedException operationFailedException) => new(OperationState.Failure(rawResponse, operationFailedException)); - - /// - /// Initializes a new instance of the class. - /// - /// The long-running operation making use of this class. Passing "this" is expected. - /// Used for diagnostic scope and exception creation. This is expected to be the instance created during the construction of your main client. - /// - /// The initial value of . Usually, long-running operation objects can be instantiated in two ways: - /// - /// - /// When calling a client's "Start<OperationName>" method, a service call is made to start the operation, and an instance is returned. - /// In this case, the response received from this service call can be passed here. - /// - /// - /// When a user instantiates an directly using a public constructor, there's no previous service call. In this case, passing null is expected. - /// - /// - /// - /// - /// The type name of the long-running operation making use of this class. Used when creating diagnostic scopes. If left null, the type name will be inferred based on the - /// parameter . - /// - /// The attributes to use during diagnostic scope creation. - /// The delay strategy when Retry-After header is not present. When it is present, the longer of the two delays will be used. - /// Default is . - public OperationInternal(IOperation operation, - ClientDiagnostics clientDiagnostics, - Response rawResponse, - string? operationTypeName = null, - IEnumerable>? scopeAttributes = null, - DelayStrategy? fallbackStrategy = null) - : base(clientDiagnostics, operationTypeName ?? operation.GetType().Name, scopeAttributes, fallbackStrategy) - { - _operation = operation; - _rawResponse = rawResponse; - _stateLock = new AsyncLockWithValue>(); - } - - internal OperationInternal(OperationState finalState) - : base(finalState.RawResponse) - { - // FinalOperation represents operation that is in final state and can't be updated. - // It implements IOperation and throws exception when UpdateStateAsync is called. - _operation = new FinalOperation(); - _rawResponse = finalState.RawResponse; - _stateLock = new AsyncLockWithValue>(finalState); - } - - public override Response RawResponse => _stateLock.TryGetValue(out var state) ? state.RawResponse : _rawResponse; - - public override bool HasCompleted => _stateLock.HasValue; - - /// - /// Returns true if the long-running operation completed successfully and has produced a final result. - /// Usage example: - /// - /// public bool HasValue => _operationInternal.HasValue; - /// - /// - /// - public bool HasValue => _stateLock.TryGetValue(out var state) && state.HasSucceeded; - - /// - /// The final result of the long-running operation. - /// Usage example: - /// - /// public T Value => _operationInternal.Value; - /// - /// - /// - /// Thrown when the operation has not completed yet. - /// Thrown when the operation has completed with failures. - public T Value - { - get - { - if (_stateLock.TryGetValue(out var state)) - { - if (state.HasSucceeded) - { - return state.Value!; - } - - throw state.OperationFailedException!; - } - - throw new InvalidOperationException("The operation has not completed yet."); - } - } - /// - /// Periodically calls until the long-running operation completes. - /// After each service call, a retry-after header may be returned to communicate that there is no reason to poll - /// for status change until the specified time has passed. - /// Headers supported are: "Retry-After", "retry-after-ms", and "x-ms-retry-after-ms", - /// Usage example: - /// - /// public async ValueTask<Response<T>> WaitForCompletionAsync(CancellationToken cancellationToken) => - /// await _operationInternal.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - /// - /// - /// - /// A controlling the request lifetime. - /// The last HTTP response received from the server, including the final result of the long-running operation. - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public async ValueTask> WaitForCompletionAsync(CancellationToken cancellationToken) - => await WaitForCompletionAsync(async: true, null, cancellationToken).ConfigureAwait(false); - - /// - /// Periodically calls until the long-running operation completes. The interval - /// between calls is defined by the parameter , but it can change based on information returned - /// from the server. After each service call, a retry-after header may be returned to communicate that there is no reason to poll - /// for status change until the specified time has passed. In this case, the maximum value between the - /// parameter and the retry-after header is chosen as the wait interval. Headers supported are: "Retry-After", "retry-after-ms", - /// and "x-ms-retry-after-ms". - /// Usage example: - /// - /// public async ValueTask<Response<T>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) => - /// await _operationInternal.WaitForCompletionAsync(pollingInterval, cancellationToken).ConfigureAwait(false); - /// - /// - /// - /// The interval between status requests to the server. - /// A controlling the request lifetime. - /// The last HTTP response received from the server, including the final result of the long-running operation. - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public async ValueTask> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) - => await WaitForCompletionAsync(async: true, pollingInterval, cancellationToken).ConfigureAwait(false); - - /// - /// Periodically calls until the long-running operation completes. - /// After each service call, a retry-after header may be returned to communicate that there is no reason to poll - /// for status change until the specified time has passed. - /// Headers supported are: "Retry-After", "retry-after-ms", and "x-ms-retry-after-ms", - /// Usage example: - /// - /// public async ValueTask<Response<T>> WaitForCompletionAsync(CancellationToken cancellationToken) => - /// await _operationInternal.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - /// - /// - /// - /// A controlling the request lifetime. - /// The last HTTP response received from the server, including the final result of the long-running operation. - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public Response WaitForCompletion(CancellationToken cancellationToken) - => WaitForCompletionAsync(async: false, null, cancellationToken).EnsureCompleted(); - - /// - /// Periodically calls until the long-running operation completes. The interval - /// between calls is defined by the , which takes into account any retry-after header that is returned - /// from the server. - /// Usage example: - /// - /// public async ValueTask<Response<T>> WaitForCompletionAsync(CancellationToken cancellationToken) => - /// await _operationInternal.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - /// - /// - /// - /// The interval between status requests to the server. - /// A controlling the request lifetime. - /// The last HTTP response received from the server, including the final result of the long-running operation. - /// Thrown if there's been any issues during the connection, or if the operation has completed with failures. - public Response WaitForCompletion(TimeSpan pollingInterval, CancellationToken cancellationToken) - => WaitForCompletionAsync(async: false, pollingInterval, cancellationToken).EnsureCompleted(); - - private async ValueTask> WaitForCompletionAsync(bool async, TimeSpan? pollingInterval, CancellationToken cancellationToken) - { - var rawResponse = await WaitForCompletionResponseAsync(async, pollingInterval, _waitForCompletionScopeName, cancellationToken).ConfigureAwait(false); - return Response.FromValue(Value, rawResponse); - } - - protected override async ValueTask UpdateStatusAsync(bool async, CancellationToken cancellationToken) - { - // If _stateLock has the final state, lockOrValue will contain that state, and no lock is acquired. - // If _stateLock doesn't have the state, GetLockOrValueAsync will acquire the lock that will be released when lockOrValue is disposed - // While _responseLock is used for the whole WaitForCompletionResponseAsync, _stateLock is used for individual calls of UpdateStatusAsync - using var asyncLock = await _stateLock.GetLockOrValueAsync(async, cancellationToken).ConfigureAwait(false); - if (asyncLock.HasValue) - { - return GetResponseFromState(asyncLock.Value); - } - - using var scope = CreateScope(_updateStatusScopeName); - try - { - var state = await _operation.UpdateStateAsync(async, cancellationToken).ConfigureAwait(false); - if (!state.HasCompleted) - { - Interlocked.Exchange(ref _rawResponse, state.RawResponse); - return state.RawResponse; - } - - if (!state.HasSucceeded && state.OperationFailedException == null) - { - state = OperationState.Failure(state.RawResponse, new RequestFailedException(state.RawResponse)); - } - - asyncLock.SetValue(state); - return GetResponseFromState(state); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - private static Response GetResponseFromState(OperationState state) - { - if (state.HasSucceeded) - { - return state.RawResponse; - } - - throw state.OperationFailedException!; - } - - private class FinalOperation : IOperation - { - public ValueTask> UpdateStateAsync(bool async, CancellationToken cancellationToken) - => throw new NotSupportedException("The operation has already completed"); - - // Unreachable path. _operation.GetRehydrationToken() is never invoked. - public RehydrationToken GetRehydrationToken() - => throw new NotSupportedException($"Getting the rehydration token of a {nameof(FinalOperation)} is not supported"); - } - } - - /// - /// An interface used by for making service calls and updating state. It's expected that - /// your long-running operation classes implement this interface. - /// - /// The final result of the long-running operation. Must match the type used in . - internal interface IOperation - { - /// - /// Calls the service and updates the state of the long-running operation. Properties directly handled by the - /// class, such as or - /// , don't need to be updated. Operation-specific properties, such - /// as "CreateOn" or "LastModified", must be manually updated by the operation implementing this - /// method. - /// Usage example: - /// - /// async ValueTask<OperationState<T>> IOperation<T>.UpdateStateAsync(bool async, CancellationToken cancellationToken)
- /// {
- /// Response<R> response = async ? <async service call> : <sync service call>;
- /// if (<operation succeeded>) return OperationState<T>.Success(response.GetRawResponse(), <parse response>);
- /// if (<operation failed>) return OperationState<T>.Failure(response.GetRawResponse());
- /// return OperationState<T>.Pending(response.GetRawResponse());
- /// } - ///
- ///
- ///
- /// true if the call should be executed asynchronously. Otherwise, false. - /// A controlling the request lifetime. - /// - /// A structure indicating the current operation state. The structure must be instantiated by one of - /// its static methods: - /// - /// Use when the operation has completed successfully. - /// Use when the operation has completed with failures. - /// Use when the operation has not completed yet. - /// - /// - ValueTask> UpdateStateAsync(bool async, CancellationToken cancellationToken); - - /// - /// Get a token that can be used to rehydrate the operation. - /// - RehydrationToken GetRehydrationToken(); - } - - /// - /// A helper structure passed to to indicate the current operation state. This structure must be - /// instantiated by one of its static methods, depending on the operation state: - /// - /// Use when the operation has completed successfully. - /// Use when the operation has completed with failures. - /// Use when the operation has not completed yet. - /// - /// - /// The final result of the long-running operation. Must match the type used in . - internal readonly struct OperationState - { - private OperationState(Response rawResponse, bool hasCompleted, bool hasSucceeded, T? value, RequestFailedException? operationFailedException) - { - RawResponse = rawResponse; - HasCompleted = hasCompleted; - HasSucceeded = hasSucceeded; - Value = value; - OperationFailedException = operationFailedException; - } - - public Response RawResponse { get; } - - public bool HasCompleted { get; } - - public bool HasSucceeded { get; } - - public T? Value { get; } - - public RequestFailedException? OperationFailedException { get; } - - /// - /// Instantiates an indicating the operation has completed successfully. - /// - /// The HTTP response obtained during the status update. - /// The final result of the long-running operation. - /// A new instance. - /// Thrown if or is null. - public static OperationState Success(Response rawResponse, T value) - { - if (rawResponse is null) - { - throw new ArgumentNullException(nameof(rawResponse)); - } - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } - - return new OperationState(rawResponse, true, true, value, default); - } - - /// - /// Instantiates an indicating the operation has completed with failures. - /// - /// The HTTP response obtained during the status update. - /// - /// The exception to throw from UpdateStatus because of the operation failure. The same exception will be thrown when - /// is called. If left null, a default exception is created based on the - /// parameter. - /// - /// A new instance. - /// Thrown if is null. - public static OperationState Failure(Response rawResponse, RequestFailedException? operationFailedException = null) - { - if (rawResponse is null) - { - throw new ArgumentNullException(nameof(rawResponse)); - } - - return new OperationState(rawResponse, true, false, default, operationFailedException); - } - - /// - /// Instantiates an indicating the operation has not completed yet. - /// - /// The HTTP response obtained during the status update. - /// A new instance. - /// Thrown if is null. - public static OperationState Pending(Response rawResponse) - { - if (rawResponse is null) - { - throw new ArgumentNullException(nameof(rawResponse)); - } - - return new OperationState(rawResponse, false, default, default, default); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationPoller.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationPoller.cs deleted file mode 100644 index 4cbd975ebb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/OperationPoller.cs +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; - -namespace Azure.Core -{ - /// - /// Implementation of LRO polling logic. - /// - internal sealed class OperationPoller - { - private readonly DelayStrategy _delayStrategy; - - public OperationPoller(DelayStrategy? strategy = null) - { - _delayStrategy = strategy ?? new FixedDelayWithNoJitterStrategy(); - } - - public ValueTask WaitForCompletionResponseAsync(Operation operation, TimeSpan? delayHint, CancellationToken cancellationToken) - => WaitForCompletionAsync(true, operation, delayHint, cancellationToken); - - public Response WaitForCompletionResponse(Operation operation, TimeSpan? delayHint, CancellationToken cancellationToken) - => WaitForCompletionAsync(false, operation, delayHint, cancellationToken).EnsureCompleted(); - - public ValueTask WaitForCompletionResponseAsync(OperationInternalBase operation, TimeSpan? delayHint, CancellationToken cancellationToken) - => WaitForCompletionAsync(true, operation, delayHint, cancellationToken); - - public Response WaitForCompletionResponse(OperationInternalBase operation, TimeSpan? delayHint, CancellationToken cancellationToken) - => WaitForCompletionAsync(false, operation, delayHint, cancellationToken).EnsureCompleted(); - - public async ValueTask> WaitForCompletionAsync(Operation operation, TimeSpan? delayHint, CancellationToken cancellationToken) where T : notnull - { - Response response = await WaitForCompletionAsync(true, operation, delayHint, cancellationToken).ConfigureAwait(false); - return Response.FromValue(operation.Value, response); - } - - public Response WaitForCompletion(Operation operation, TimeSpan? delayHint, CancellationToken cancellationToken) where T : notnull - { - Response response = WaitForCompletionAsync(false, operation, delayHint, cancellationToken).EnsureCompleted(); - return Response.FromValue(operation.Value, response); - } - - public async ValueTask> WaitForCompletionAsync(OperationInternal operation, TimeSpan? delayHint, CancellationToken cancellationToken) where T : notnull - { - Response response = await WaitForCompletionAsync(true, operation, delayHint, cancellationToken).ConfigureAwait(false); - return Response.FromValue(operation.Value, response); - } - - public Response WaitForCompletion(OperationInternal operation, TimeSpan? delayHint, CancellationToken cancellationToken) where T : notnull - { - Response response = WaitForCompletionAsync(false, operation, delayHint, cancellationToken).EnsureCompleted(); - return Response.FromValue(operation.Value, response); - } - - private async ValueTask WaitForCompletionAsync(bool async, Operation operation, TimeSpan? delayHint, CancellationToken cancellationToken) - { - int retryNumber = 0; - while (true) - { - Response response = async ? await operation.UpdateStatusAsync(cancellationToken).ConfigureAwait(false) : operation.UpdateStatus(cancellationToken); - if (operation.HasCompleted) - { - return operation.GetRawResponse(); - } - - var strategy = delayHint.HasValue ? new FixedDelayWithNoJitterStrategy(delayHint.Value) : _delayStrategy; - - await Delay(async, strategy.GetNextDelay(response, ++retryNumber), cancellationToken).ConfigureAwait(false); - } - } - - private async ValueTask WaitForCompletionAsync(bool async, OperationInternalBase operation, TimeSpan? delayHint, CancellationToken cancellationToken) - { - int retryNumber = 0; - while (true) - { - Response response = async ? await operation.UpdateStatusAsync(cancellationToken).ConfigureAwait(false) : operation.UpdateStatus(cancellationToken); - if (operation.HasCompleted) - { - return operation.RawResponse; - } - - var strategy = delayHint.HasValue ? new FixedDelayWithNoJitterStrategy(delayHint.Value) : _delayStrategy; - - await Delay(async, strategy.GetNextDelay(response, ++retryNumber), cancellationToken).ConfigureAwait(false); - } - } - - private static async ValueTask Delay(bool async, TimeSpan delay, CancellationToken cancellationToken) - { - if (async) - { - await Task.Delay(delay, cancellationToken).ConfigureAwait(false); - } - else if (cancellationToken.CanBeCanceled) - { - if (cancellationToken.WaitHandle.WaitOne(delay)) - { - cancellationToken.ThrowIfCancellationRequested(); - } - } - else - { - Thread.Sleep(delay); - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/Page.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/Page.cs deleted file mode 100644 index 1438fdfd5f..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/Page.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System.Collections.Generic; -using System.Linq; - -namespace Azure.Core -{ - internal static class Page - { - public static Page FromValues(IEnumerable values, string continuationToken, Response response) => - Page.FromValues(values.ToList(), continuationToken, response); - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/PageableHelpers.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/PageableHelpers.cs deleted file mode 100644 index 4d15951fef..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/PageableHelpers.cs +++ /dev/null @@ -1,556 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Text; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; - -namespace Azure.Core -{ - internal static class PageableHelpers - { - private static readonly byte[] DefaultItemPropertyName = Encoding.UTF8.GetBytes("value"); - private static readonly byte[] DefaultNextLinkPropertyName = Encoding.UTF8.GetBytes("nextLink"); - - public static AsyncPageable CreateAsyncPageable(Func? createFirstPageRequest, Func? createNextPageRequest, Func? Values, string? NextLink)> responseParser, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string scopeName, RequestContext? requestContext = null) where T : notnull - { - return new AsyncPageableWrapper(new PageableImplementation(createFirstPageRequest, createNextPageRequest, responseParser, pipeline, clientDiagnostics, scopeName, null, requestContext)); - } - - public static AsyncPageable CreateAsyncPageable(Func? createFirstPageRequest, Func? createNextPageRequest, Func valueFactory, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string scopeName, string? itemPropertyName, string? nextLinkPropertyName, CancellationToken cancellationToken) where T : notnull - { - return new AsyncPageableWrapper(new PageableImplementation(null, createFirstPageRequest, createNextPageRequest, valueFactory, pipeline, clientDiagnostics, scopeName, itemPropertyName, nextLinkPropertyName, null, cancellationToken, null)); - } - - public static AsyncPageable CreateAsyncPageable(Func? createFirstPageRequest, Func? createNextPageRequest, Func valueFactory, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string scopeName, string? itemPropertyName, string? nextLinkPropertyName, RequestContext? requestContext = null) where T : notnull - { - return new AsyncPageableWrapper(new PageableImplementation(null, createFirstPageRequest, createNextPageRequest, valueFactory, pipeline, clientDiagnostics, scopeName, itemPropertyName, nextLinkPropertyName, null, requestContext?.CancellationToken, requestContext?.ErrorOptions)); - } - - public static AsyncPageable CreateAsyncPageable(Response initialResponse, Func? createNextPageRequest, Func valueFactory, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string scopeName, string? itemPropertyName, string? nextLinkPropertyName, CancellationToken cancellationToken) where T : notnull - { - return new AsyncPageableWrapper(new PageableImplementation(initialResponse, null, createNextPageRequest, valueFactory, pipeline, clientDiagnostics, scopeName, itemPropertyName, nextLinkPropertyName, null, cancellationToken, null)); - } - - public static Pageable CreatePageable(Func? createFirstPageRequest, Func? createNextPageRequest, Func? Values, string? NextLink)> responseParser, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string scopeName, RequestContext? requestContext = null) where T : notnull - { - return new PageableWrapper(new PageableImplementation(createFirstPageRequest, createNextPageRequest, responseParser, pipeline, clientDiagnostics, scopeName, null, requestContext)); - } - - public static Pageable CreatePageable(Func? createFirstPageRequest, Func? createNextPageRequest, Func valueFactory, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string scopeName, string? itemPropertyName, string? nextLinkPropertyName, CancellationToken cancellationToken) where T : notnull - { - return new PageableWrapper(new PageableImplementation(null, createFirstPageRequest, createNextPageRequest, valueFactory, pipeline, clientDiagnostics, scopeName, itemPropertyName, nextLinkPropertyName, null, cancellationToken, null)); - } - - public static Pageable CreatePageable(Func? createFirstPageRequest, Func? createNextPageRequest, Func valueFactory, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string scopeName, string? itemPropertyName, string? nextLinkPropertyName, RequestContext? requestContext = null) where T : notnull - { - return new PageableWrapper(new PageableImplementation(null, createFirstPageRequest, createNextPageRequest, valueFactory, pipeline, clientDiagnostics, scopeName, itemPropertyName, nextLinkPropertyName, null, requestContext?.CancellationToken, requestContext?.ErrorOptions)); - } - - public static Pageable CreatePageable(Response initialResponse, Func? createNextPageRequest, Func valueFactory, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string scopeName, string? itemPropertyName, string? nextLinkPropertyName, CancellationToken cancellationToken) where T : notnull - { - return new PageableWrapper(new PageableImplementation(initialResponse, null, createNextPageRequest, valueFactory, pipeline, clientDiagnostics, scopeName, itemPropertyName, nextLinkPropertyName, null, cancellationToken, null)); - } - - public static async ValueTask>> CreateAsyncPageable(WaitUntil waitUntil, HttpMessage message, Func? createNextPageMethod, Func valueFactory, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, OperationFinalStateVia finalStateVia, string scopeName, string? itemPropertyName, string? nextLinkPropertyName, RequestContext? requestContext = null) where T : notnull - { - AsyncPageable ResultSelector(Response r) => new AsyncPageableWrapper(new PageableImplementation(r, null, createNextPageMethod, valueFactory, pipeline, clientDiagnostics, scopeName, itemPropertyName, nextLinkPropertyName, null, requestContext?.CancellationToken, requestContext?.ErrorOptions)); - - var response = await pipeline.ProcessMessageAsync(message, requestContext).ConfigureAwait(false); - var operation = new ProtocolOperation>(clientDiagnostics, pipeline, message.Request, response, finalStateVia, scopeName, ResultSelector); - if (waitUntil == WaitUntil.Completed) - { - await operation.WaitForCompletionAsync(requestContext?.CancellationToken ?? default).ConfigureAwait(false); - } - return operation; - } - - public static Operation> CreatePageable(WaitUntil waitUntil, HttpMessage message, Func? createNextPageMethod, Func valueFactory, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, OperationFinalStateVia finalStateVia, string scopeName, string? itemPropertyName, string? nextLinkPropertyName, RequestContext? requestContext = null) where T : notnull - { - Pageable ResultSelector(Response r) => new PageableWrapper(new PageableImplementation(r, null, createNextPageMethod, valueFactory, pipeline, clientDiagnostics, scopeName, itemPropertyName, nextLinkPropertyName, null, requestContext?.CancellationToken, requestContext?.ErrorOptions)); - - var response = pipeline.ProcessMessage(message, requestContext); - var operation = new ProtocolOperation>(clientDiagnostics, pipeline, message.Request, response, finalStateVia, scopeName, ResultSelector); - if (waitUntil == WaitUntil.Completed) - { - operation.WaitForCompletion(requestContext?.CancellationToken ?? default); - } - return operation; - } - - public static Pageable CreateEnumerable(Func> firstPageFunc, Func>? nextPageFunc, int? pageSize = default) where T : notnull - { - Func> first = (_, pageSizeHint) => firstPageFunc(pageSizeHint); - return new FuncPageable(first, nextPageFunc, pageSize); - } - - public static AsyncPageable CreateAsyncEnumerable(Func>> firstPageFunc, Func>>? nextPageFunc, int? pageSize = default) where T : notnull - { - Func>> first = (_, pageSizeHint) => firstPageFunc(pageSizeHint); - return new FuncAsyncPageable(first, nextPageFunc, pageSize); - } - - internal class FuncAsyncPageable : AsyncPageable where T : notnull - { - private readonly Func>> _firstPageFunc; - private readonly Func>>? _nextPageFunc; - private readonly int? _defaultPageSize; - - public FuncAsyncPageable(Func>> firstPageFunc, Func>>? nextPageFunc, int? defaultPageSize = default) - { - _firstPageFunc = firstPageFunc; - _nextPageFunc = nextPageFunc; - _defaultPageSize = defaultPageSize; - } - - public override async IAsyncEnumerable> AsPages(string? continuationToken = default, int? pageSizeHint = default) - { - Func>>? pageFunc = string.IsNullOrEmpty(continuationToken) ? _firstPageFunc : _nextPageFunc; - - if (pageFunc == null) - { - yield break; - } - - int? pageSize = pageSizeHint ?? _defaultPageSize; - do - { - Page pageResponse = await pageFunc(continuationToken, pageSize).ConfigureAwait(false); - yield return pageResponse; - continuationToken = pageResponse.ContinuationToken; - pageFunc = _nextPageFunc; - } while (!string.IsNullOrEmpty(continuationToken) && pageFunc != null); - } - } - - internal class FuncPageable : Pageable where T : notnull - { - private readonly Func> _firstPageFunc; - private readonly Func>? _nextPageFunc; - private readonly int? _defaultPageSize; - - public FuncPageable(Func> firstPageFunc, Func>? nextPageFunc, int? defaultPageSize = default) - { - _firstPageFunc = firstPageFunc; - _nextPageFunc = nextPageFunc; - _defaultPageSize = defaultPageSize; - } - - public override IEnumerable> AsPages(string? continuationToken = default, int? pageSizeHint = default) - { - Func>? pageFunc = string.IsNullOrEmpty(continuationToken) ? _firstPageFunc : _nextPageFunc; - - if (pageFunc == null) - { - yield break; - } - - int? pageSize = pageSizeHint ?? _defaultPageSize; - do - { - Page pageResponse = pageFunc(continuationToken, pageSize); - yield return pageResponse; - continuationToken = pageResponse.ContinuationToken; - pageFunc = _nextPageFunc; - } while (!string.IsNullOrEmpty(continuationToken) && pageFunc != null); - } - } - - internal class AsyncPageableWrapper : AsyncPageable where T : notnull - { - private readonly PageableImplementation _implementation; - - public AsyncPageableWrapper(PageableImplementation implementation) - { - _implementation = implementation; - } - - public override IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) => _implementation.GetAsyncEnumerator(cancellationToken); - public override IAsyncEnumerable> AsPages(string? continuationToken = null, int? pageSizeHint = null) => _implementation.AsPagesAsync(continuationToken, pageSizeHint, default); - } - - internal class PageableWrapper : Pageable where T : notnull - { - private readonly PageableImplementation _implementation; - - public PageableWrapper(PageableImplementation implementation) - { - _implementation = implementation; - } - - public override IEnumerator GetEnumerator() => _implementation.GetEnumerator(); - public override IEnumerable> AsPages(string? continuationToken = null, int? pageSizeHint = null) => _implementation.AsPages(continuationToken, pageSizeHint); - } - - internal class PageableImplementation - { - private readonly Response? _initialResponse; - private readonly Func? _createFirstPageRequest; - private readonly Func? _createNextPageRequest; - private readonly HttpPipeline _pipeline; - private readonly ClientDiagnostics _clientDiagnostics; - private readonly Func? _valueFactory; - private readonly Func? Values, string? NextLink)>? _responseParser; - private readonly string _scopeName; - private readonly byte[] _itemPropertyName; - private readonly byte[] _nextLinkPropertyName; - private readonly int? _defaultPageSize; - private readonly CancellationToken _cancellationToken; - private readonly ErrorOptions? _errorOptions; - - public PageableImplementation( - Response? initialResponse, - Func? createFirstPageRequest, - Func? createNextPageRequest, - Func valueFactory, - HttpPipeline pipeline, - ClientDiagnostics clientDiagnostics, - string scopeName, - string? itemPropertyName, - string? nextLinkPropertyName, - int? defaultPageSize, - CancellationToken? cancellationToken, - ErrorOptions? errorOptions) - { - _initialResponse = initialResponse; - _createFirstPageRequest = createFirstPageRequest; - _createNextPageRequest = createNextPageRequest; - _valueFactory = typeof(T) == typeof(BinaryData) ? null : valueFactory; - _responseParser = null; - _pipeline = pipeline; - _clientDiagnostics = clientDiagnostics; - _scopeName = scopeName; - _itemPropertyName = itemPropertyName != null ? Encoding.UTF8.GetBytes(itemPropertyName) : DefaultItemPropertyName; - _nextLinkPropertyName = nextLinkPropertyName != null ? Encoding.UTF8.GetBytes(nextLinkPropertyName) : DefaultNextLinkPropertyName; - _defaultPageSize = defaultPageSize; - _cancellationToken = cancellationToken ?? default; - _errorOptions = errorOptions ?? ErrorOptions.Default; - } - - public PageableImplementation(Func? createFirstPageRequest, Func? createNextPageRequest, Func? Values, string? NextLink)> responseParser, HttpPipeline pipeline, ClientDiagnostics clientDiagnostics, string scopeName, int? defaultPageSize, RequestContext? requestContext) - { - _createFirstPageRequest = createFirstPageRequest; - _createNextPageRequest = createNextPageRequest; - _valueFactory = null; - _responseParser = responseParser; - _pipeline = pipeline; - _clientDiagnostics = clientDiagnostics; - _scopeName = scopeName; - _itemPropertyName = Array.Empty(); - _nextLinkPropertyName = Array.Empty(); - _defaultPageSize = defaultPageSize; - _cancellationToken = requestContext?.CancellationToken ?? default; - _errorOptions = requestContext?.ErrorOptions ?? ErrorOptions.Default; - } - - public async IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) - { - string? nextLink = null; - do - { - var response = await GetNextResponseAsync(null, nextLink, cancellationToken).ConfigureAwait(false); - if (!TryGetItemsFromResponse(response, out nextLink, out var jsonArray, out var items)) - { - continue; - } - - if (_valueFactory != null) - { - foreach (var jsonItem in jsonArray) - { - yield return _valueFactory(jsonItem); - } - } - else - { - foreach (var item in items!) - { - yield return item; - } - } - } while (!string.IsNullOrEmpty(nextLink)); - } - - public async IAsyncEnumerable> AsPagesAsync(string? continuationToken, int? pageSizeHint, [EnumeratorCancellation] CancellationToken cancellationToken) - { - string? nextLink = continuationToken; - do - { - var response = await GetNextResponseAsync(pageSizeHint, nextLink, cancellationToken).ConfigureAwait(false); - if (response is null) - { - yield break; - } - yield return CreatePage(response, out nextLink); - } while (!string.IsNullOrEmpty(nextLink)); - } - - public IEnumerator GetEnumerator() - { - string? nextLink = null; - do - { - var response = GetNextResponse(null, nextLink); - if (!TryGetItemsFromResponse(response, out nextLink, out var jsonArray, out var items)) - { - continue; - } - - if (_valueFactory != null) - { - foreach (var jsonItem in jsonArray) - { - yield return _valueFactory(jsonItem); - } - } - else - { - foreach (var item in items!) - { - yield return item; - } - } - } while (!string.IsNullOrEmpty(nextLink)); - } - - public IEnumerable> AsPages(string? continuationToken, int? pageSizeHint) - { - string? nextLink = continuationToken; - do - { - var response = GetNextResponse(pageSizeHint, nextLink); - if (response is null) - { - yield break; - } - yield return CreatePage(response, out nextLink); - } while (!string.IsNullOrEmpty(nextLink)); - } - - private Response? GetNextResponse(int? pageSizeHint, string? nextLink) - { - var message = CreateMessage(pageSizeHint, nextLink, out var response); - if (message == null) - { - return response; - } - - using DiagnosticScope scope = _clientDiagnostics.CreateScope(_scopeName); - scope.Start(); - try - { - _pipeline.Send(message, _cancellationToken); - return GetResponse(message); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - private async ValueTask GetNextResponseAsync(int? pageSizeHint, string? nextLink, CancellationToken cancellationToken) - { - var message = CreateMessage(pageSizeHint, nextLink, out var response); - if (message == null) - { - return response; - } - - using DiagnosticScope scope = _clientDiagnostics.CreateScope(_scopeName); - scope.Start(); - try - { - if (cancellationToken.CanBeCanceled && _cancellationToken.CanBeCanceled) - { - using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cancellationToken); - await _pipeline.SendAsync(message, cts.Token).ConfigureAwait(false); - } - else - { - var ct = cancellationToken.CanBeCanceled ? cancellationToken : _cancellationToken; - await _pipeline.SendAsync(message, ct).ConfigureAwait(false); - } - - return GetResponse(message); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - private HttpMessage? CreateMessage(int? pageSizeHint, string? nextLink, out Response? response) - { - if (!string.IsNullOrEmpty(nextLink)) - { - response = null; - return _createNextPageRequest?.Invoke(pageSizeHint ?? _defaultPageSize, nextLink!); - } - - if (_createFirstPageRequest == null) - { - response = _initialResponse; - return null; - } - - response = null; - return _createFirstPageRequest(pageSizeHint ?? _defaultPageSize); - } - - private Response GetResponse(HttpMessage message) - { - if (message.Response.IsError && _errorOptions != ErrorOptions.NoThrow) - { - throw new RequestFailedException(message.Response); - } - - return message.Response; - } - - // Tries to parse response either using default logic or by using custom parser - // Returns true when either jsonArrayEnumerator is not default or items is not null - private bool TryGetItemsFromResponse(Response? response, out string? nextLink, out JsonElement.ArrayEnumerator jsonArrayEnumerator, out List? items) - { - if (response is null) - { - nextLink = default; - jsonArrayEnumerator = default; - items = default; - return false; - } - - if (_valueFactory is not null) - { - items = default; - var document = response.ContentStream != null ? JsonDocument.Parse(response.ContentStream) : JsonDocument.Parse(response.Content); - if (_createNextPageRequest is null && _itemPropertyName.Length == 0) // Pageable is a simple collection of elements - { - nextLink = null; - jsonArrayEnumerator = document.RootElement.EnumerateArray(); - return true; - } - - nextLink = document.RootElement.TryGetProperty(_nextLinkPropertyName, out var nextLinkValue) ? nextLinkValue.GetString() : null; - if (document.RootElement.TryGetProperty(_itemPropertyName, out var itemsValue)) - { - jsonArrayEnumerator = itemsValue.EnumerateArray(); - return true; - } - - jsonArrayEnumerator = default; - return false; - } - - jsonArrayEnumerator = default; - // _responseParser will be null when T is BinaryData - var parsedResponse = _responseParser?.Invoke(response) ?? ParseResponseForBinaryData(response, _itemPropertyName, _nextLinkPropertyName); - items = parsedResponse.Values; - nextLink = parsedResponse.NextLink; - return items is not null; - } - - private Page CreatePage(Response response, out string? nextLink) - { - if (!TryGetItemsFromResponse(response, out nextLink, out var jsonArray, out var items)) - { - return Page.FromValues(Array.Empty(), nextLink, response); - } - - if (_valueFactory == null) - { - return Page.FromValues(items!, nextLink, response); - } - - var values = new List(); - foreach (var jsonItem in jsonArray) - { - values.Add(_valueFactory(jsonItem)); - } - - return Page.FromValues(values, nextLink, response); - } - } - - // This method is used to avoid calling _valueFactory for BinaryData cause it requires instantiation of strings. - // Remove it when `JsonElement` provides access to its UTF8 buffer. - // See also PageableMethodsWriterExtensions.GetValueFactory - private static (List? Values, string? NextLink) ParseResponseForBinaryData(Response response, byte[] itemPropertyName, byte[] nextLinkPropertyName) - { - var content = response.Content.ToMemory(); - var r = new Utf8JsonReader(content.Span); - - List? items = null; - string? nextLink = null; - - if (!r.Read() || r.TokenType != JsonTokenType.StartObject) - { - throw new InvalidOperationException("Expected response to be JSON object"); - } - - while (r.Read()) - { - switch (r.TokenType) - { - case JsonTokenType.PropertyName: - if (r.ValueTextEquals(nextLinkPropertyName)) - { - r.Read(); - nextLink = r.GetString(); - } - else if (r.ValueTextEquals(itemPropertyName)) - { - if (!r.Read() || r.TokenType != JsonTokenType.StartArray) - { - throw new InvalidOperationException($"Expected {Encoding.UTF8.GetString(itemPropertyName)} to be an array"); - } - - while (r.Read() && r.TokenType != JsonTokenType.EndArray) - { - var element = ReadBinaryData(ref r, content); - items ??= new List(); - items.Add((T)element); - } - } - else - { - r.Skip(); - } - break; - case JsonTokenType.EndObject: - break; - - default: - throw new Exception("Unexpected token"); - } - } - - return (items, nextLink); - - static object ReadBinaryData(ref Utf8JsonReader r, in ReadOnlyMemory content) - { - switch (r.TokenType) - { - case JsonTokenType.StartObject or JsonTokenType.StartArray: - int elementStart = (int)r.TokenStartIndex; - r.Skip(); - int elementEnd = (int)r.TokenStartIndex; - int length = elementEnd - elementStart + 1; - return new BinaryData(content.Slice(elementStart, length)); - case JsonTokenType.String: - return new BinaryData(content.Slice((int)r.TokenStartIndex, r.ValueSpan.Length + 2 /* open and closing quotes are not captured in the value span */)); - default: - return new BinaryData(content.Slice((int)r.TokenStartIndex, r.ValueSpan.Length)); - } - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/PropertyReferenceTypeAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/PropertyReferenceTypeAttribute.cs deleted file mode 100644 index 141b350a5e..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/PropertyReferenceTypeAttribute.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -namespace Azure.Core -{ - /// - /// An attribute class indicating to Autorest a reference type for code generation. - /// - [AttributeUsage(AttributeTargets.Class)] - internal class PropertyReferenceTypeAttribute : Attribute - { - /// - /// Instantiate a new reference type attribute. - /// - /// An array of property names that are optional when comparing the type. - public PropertyReferenceTypeAttribute(string[] optionalProperties) - : this(optionalProperties, Array.Empty()) - { - } - - /// - /// Instantiate a new reference type attribute. - /// - /// An array of property names that are optional when comparing the type. - /// An array of internal properties to include for the reference type when evaluating whether type - /// replacement should occur. When evaluating a type for replacement with a reference type, all internal properties are considered on the - /// type to be replaced. Thus this parameter can be used to specify internal properties to allow replacement to occur on a type with internal - /// properties. - public PropertyReferenceTypeAttribute(string[] optionalProperties, string[] internalPropertiesToInclude) - { - OptionalProperties = optionalProperties; - InternalPropertiesToInclude = internalPropertiesToInclude; - } - - public string[] InternalPropertiesToInclude { get; } - - /// - /// Instantiate a new reference type attribute. - /// - public PropertyReferenceTypeAttribute() - : this(Array.Empty(), Array.Empty()) - { - } - - /// - /// Get an array of property names that are optional when comparing the type. - /// - public string[] OptionalProperties { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ProtocolOperation.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ProtocolOperation.cs deleted file mode 100644 index ce76a07848..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ProtocolOperation.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; - -namespace Azure.Core -{ - internal class ProtocolOperation : Operation, IOperation where T : notnull - { - private readonly Func _resultSelector; - private readonly OperationInternal _operation; - private readonly IOperation _nextLinkOperation; - - internal ProtocolOperation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response, OperationFinalStateVia finalStateVia, string scopeName, Func resultSelector) - { - _resultSelector = resultSelector; - _nextLinkOperation = NextLinkOperationImplementation.Create(pipeline, request.Method, request.Uri.ToUri(), response, finalStateVia); - _operation = new OperationInternal(this, clientDiagnostics, response, scopeName); - } - -#pragma warning disable CA1822 - // This scenario is currently unsupported. - // See: https://github.com/Azure/autorest.csharp/issues/2158. - /// - public override string Id => throw new NotSupportedException(); -#pragma warning restore CA1822 - - /// - public override RehydrationToken? GetRehydrationToken() => ((IOperation)this).GetRehydrationToken(); - - RehydrationToken IOperation.GetRehydrationToken() => _nextLinkOperation.GetRehydrationToken(); - - /// - public override T Value => _operation.Value; - - /// - public override bool HasCompleted => _operation.HasCompleted; - - /// - public override bool HasValue => _operation.HasValue; - - /// - public override Response GetRawResponse() => _operation.RawResponse; - - /// - public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); - - /// - public override ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); - - /// - public override ValueTask> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken); - - /// - public override ValueTask> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken); - - async ValueTask> IOperation.UpdateStateAsync(bool async, CancellationToken cancellationToken) - { - var state = await _nextLinkOperation.UpdateStateAsync(async, cancellationToken).ConfigureAwait(false); - if (state.HasSucceeded) - { - return OperationState.Success(state.RawResponse, _resultSelector(state.RawResponse)); - } - - if (state.HasCompleted) - { - return OperationState.Failure(state.RawResponse, state.OperationFailedException); - } - - return OperationState.Pending(state.RawResponse); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/RawRequestUriBuilder.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/RawRequestUriBuilder.cs deleted file mode 100644 index f48b1f6ed6..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/RawRequestUriBuilder.cs +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; - -namespace Azure.Core -{ - internal class RawRequestUriBuilder: RequestUriBuilder - { - private const string SchemeSeparator = "://"; - private const char HostSeparator = '/'; - private const char PortSeparator = ':'; - private static readonly char[] HostOrPort = { HostSeparator, PortSeparator }; - private const char QueryBeginSeparator = '?'; - private const char QueryContinueSeparator = '&'; - private const char QueryValueSeparator = '='; - - private RawWritingPosition? _position; - - private static void GetQueryParts(ReadOnlySpan queryUnparsed, out ReadOnlySpan name, out ReadOnlySpan value) - { - int separatorIndex = queryUnparsed.IndexOf(QueryValueSeparator); - if (separatorIndex == -1) - { - name = queryUnparsed; - value = ReadOnlySpan.Empty; - } - else - { - name = queryUnparsed.Slice(0, separatorIndex); - value = queryUnparsed.Slice(separatorIndex + 1); - } - } - - public void AppendRaw(string value, bool escape) - { - AppendRaw(value.AsSpan(), escape); - } - - private void AppendRaw(ReadOnlySpan value, bool escape) - { - if (_position == null) - { - if (HasQuery) - { - _position = RawWritingPosition.Query; - } - else if (HasPath) - { - _position = RawWritingPosition.Path; - } - else if (!string.IsNullOrEmpty(Host)) - { - _position = RawWritingPosition.Host; - } - else - { - _position = RawWritingPosition.Scheme; - } - } - - while (!value.IsEmpty) - { - if (_position == RawWritingPosition.Scheme) - { - int separator = value.IndexOf(SchemeSeparator.AsSpan(), StringComparison.InvariantCultureIgnoreCase); - if (separator == -1) - { - Scheme += value.ToString(); - value = ReadOnlySpan.Empty; - } - else - { - Scheme += value.Slice(0, separator).ToString(); - // TODO: Find a better way to map schemes to default ports - Port = string.Equals(Scheme, "https", StringComparison.OrdinalIgnoreCase) ? 443 : 80; - value = value.Slice(separator + SchemeSeparator.Length); - _position = RawWritingPosition.Host; - } - } - else if (_position == RawWritingPosition.Host) - { - int separator = value.IndexOfAny(HostOrPort); - if (separator == -1) - { - if (!HasPath) - { - Host += value.ToString(); - value = ReadOnlySpan.Empty; - } - else - { - // All Host information must be written before Path information - // If Path already has information, we transition to writing Path - _position = RawWritingPosition.Path; - } - } - else - { - Host += value.Slice(0, separator).ToString(); - _position = value[separator] == HostSeparator ? RawWritingPosition.Path : RawWritingPosition.Port; - value = value.Slice(separator + 1); - } - } - else if (_position == RawWritingPosition.Port) - { - int separator = value.IndexOf(HostSeparator); - if (separator == -1) - { -#if NETCOREAPP2_1_OR_GREATER - Port = int.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture); -#else - Port = int.Parse(value.ToString(), CultureInfo.InvariantCulture); -#endif - value = ReadOnlySpan.Empty; - } - else - { -#if NETCOREAPP2_1_OR_GREATER - Port = int.Parse(value.Slice(0, separator), NumberStyles.Integer, CultureInfo.InvariantCulture); -#else - Port = int.Parse(value.Slice(0, separator).ToString(), CultureInfo.InvariantCulture); -#endif - value = value.Slice(separator + 1); - } - // Port cannot be split (like Host), so always transition to Path when Port is parsed - _position = RawWritingPosition.Path; - } - else if (_position == RawWritingPosition.Path) - { - int separator = value.IndexOf(QueryBeginSeparator); - if (separator == -1) - { - AppendPath(value, escape); - value = ReadOnlySpan.Empty; - } - else - { - AppendPath(value.Slice(0, separator), escape); - value = value.Slice(separator + 1); - _position = RawWritingPosition.Query; - } - } - else if (_position == RawWritingPosition.Query) - { - int separator = value.IndexOf(QueryContinueSeparator); - if (separator == 0) - { - value = value.Slice(1); - } - else if (separator == -1) - { - GetQueryParts(value, out var queryName, out var queryValue); - AppendQuery(queryName, queryValue, escape); - value = ReadOnlySpan.Empty; - } - else - { - GetQueryParts(value.Slice(0, separator), out var queryName, out var queryValue); - AppendQuery(queryName, queryValue, escape); - value = value.Slice(separator + 1); - } - } - } - } - - private enum RawWritingPosition - { - Scheme, - Host, - Port, - Path, - Query - } - - public void AppendRawNextLink(string nextLink, bool escape) - { - // If it is an absolute link, we use the nextLink as the entire url - if (nextLink.StartsWith(Uri.UriSchemeHttp, StringComparison.InvariantCultureIgnoreCase)) - { - Reset(new Uri(nextLink)); - return; - } - - AppendRaw(nextLink, escape); - } - - public void AppendQuery(string name, bool value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, float value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, DateTimeOffset value, string format, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value, format), escape); - - public void AppendQuery(string name, TimeSpan value, string format, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value, format), escape); - - public void AppendQuery(string name, double value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, decimal value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, int value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, long value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, TimeSpan value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, byte[] value, string format, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value, format), escape); - - public void AppendQuery(string name, Guid value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQueryDelimited(string name, IEnumerable value, string delimiter, string? format = null, bool escape = true) - { - delimiter ??= ","; - IEnumerable stringValues = value.Select(v => TypeFormatters.ConvertToString(v, format)); - AppendQuery(name, string.Join(delimiter, stringValues), escape); - } - - public void AppendPathDelimited(IEnumerable value, string delimiter, string? format = null, bool escape = true) - { - delimiter ??= ","; - IEnumerable stringValues = value.Select(v => TypeFormatters.ConvertToString(v, format)); - AppendPath(string.Join(delimiter, stringValues), escape); - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ReferenceTypeAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ReferenceTypeAttribute.cs deleted file mode 100644 index 04e86cc394..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/ReferenceTypeAttribute.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -namespace Azure.Core -{ - /// - /// An attribute class indicating to Autorest a reference type for code generation. - /// - [AttributeUsage(AttributeTargets.Class)] - internal class ReferenceTypeAttribute : Attribute - { - /// - /// Instantiate a new reference type attribute. - /// - /// An array of property names that are optional when comparing the type. - public ReferenceTypeAttribute(string[] optionalProperties) - { - OptionalProperties = optionalProperties; - } - - /// - /// Instantiate a new reference type attribute. - /// - public ReferenceTypeAttribute() - : this(Array.Empty()) - { - } - - /// - /// Get an array of property names that are optional when comparing the type. - /// - public string[] OptionalProperties { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/SequentialDelayStrategy.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/SequentialDelayStrategy.cs deleted file mode 100644 index 5185fa1201..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/SequentialDelayStrategy.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -#nullable enable - -namespace Azure.Core -{ - /// - /// A delay strategy that uses a fixed sequence of delays with no jitter applied. This is used by management LROs. - /// - internal class SequentialDelayStrategy : DelayStrategy - { - private static readonly TimeSpan[] _pollingSequence = new TimeSpan[] - { - TimeSpan.FromSeconds(1), - TimeSpan.FromSeconds(1), - TimeSpan.FromSeconds(1), - TimeSpan.FromSeconds(2), - TimeSpan.FromSeconds(4), - TimeSpan.FromSeconds(8), - TimeSpan.FromSeconds(16), - TimeSpan.FromSeconds(32) - }; - private static readonly TimeSpan _maxDelay = _pollingSequence[_pollingSequence.Length - 1]; - - public SequentialDelayStrategy() : base(_maxDelay, 0) - { - } - - protected override TimeSpan GetNextDelayCore(Response? response, int retryNumber) - { - int index = retryNumber - 1; - return index >= _pollingSequence.Length ? _maxDelay : _pollingSequence[index]; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/SerializationConstructorAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/SerializationConstructorAttribute.cs deleted file mode 100644 index fbe9465541..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/SerializationConstructorAttribute.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -namespace Azure.Core -{ - /// - /// An attribute class indicating to AutoRest which constructor to use for serialization. - /// - [AttributeUsage(AttributeTargets.Constructor)] - internal class SerializationConstructorAttribute : Attribute - { - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/SharedExtensions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/SharedExtensions.cs deleted file mode 100644 index 215fd316e5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/SharedExtensions.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; - -namespace Azure.ResourceManager -{ - /// - /// helper class - /// - internal static class SharedExtensions - { - /// - /// Collects the segments in a resource identifier into a string - /// - /// the resource identifier - /// - public static string SubstringAfterProviderNamespace(this ResourceIdentifier resourceId) - { - const string providersKey = "/providers/"; - var rawId = resourceId.ToString(); - var indexOfProviders = rawId.LastIndexOf(providersKey, StringComparison.InvariantCultureIgnoreCase); - if (indexOfProviders < 0) - return string.Empty; - var whateverRemains = rawId.Substring(indexOfProviders + providersKey.Length); - var firstSlashIndex = whateverRemains.IndexOf('/'); - if (firstSlashIndex < 0) - return string.Empty; - return whateverRemains.Substring(firstSlashIndex + 1); - } - - /// - /// An extension method for supporting replacing one dictionary content with another one. - /// This is used to support resource tags. - /// - /// The destination dictionary in which the content will be replaced. - /// The source dictionary from which the content is copied from. - /// The destination dictionary that has been altered. - public static IDictionary ReplaceWith(this IDictionary dest, IDictionary src) - { - dest.Clear(); - foreach (var kv in src) - { - dest.Add(kv); - } - - return dest; - } - - public static async Task FirstOrDefaultAsync( - this AsyncPageable source, - Func predicate, - CancellationToken token = default) - where TSource : notnull - { - if (source == null) - throw new ArgumentNullException(nameof(source)); - if (predicate == null) - throw new ArgumentNullException(nameof(predicate)); - - token.ThrowIfCancellationRequested(); - - await foreach (var item in source.ConfigureAwait(false)) - { - token.ThrowIfCancellationRequested(); - - if (predicate(item)) - { - return item; - } - } - - return default; - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/TaskExtensions.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/TaskExtensions.cs deleted file mode 100644 index 9748653782..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/TaskExtensions.cs +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Threading; -using System.Threading.Tasks; - -namespace Azure.Core.Pipeline -{ - internal static class TaskExtensions - { - public static WithCancellationTaskAwaitable AwaitWithCancellation(this Task task, CancellationToken cancellationToken) - => new WithCancellationTaskAwaitable(task, cancellationToken); - - public static WithCancellationTaskAwaitable AwaitWithCancellation(this Task task, CancellationToken cancellationToken) - => new WithCancellationTaskAwaitable(task, cancellationToken); - - public static WithCancellationValueTaskAwaitable AwaitWithCancellation(this ValueTask task, CancellationToken cancellationToken) - => new WithCancellationValueTaskAwaitable(task, cancellationToken); - - public static T EnsureCompleted(this Task task) - { -#if DEBUG - VerifyTaskCompleted(task.IsCompleted); -#endif -#pragma warning disable AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead. - return task.GetAwaiter().GetResult(); -#pragma warning restore AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead. - } - - public static void EnsureCompleted(this Task task) - { -#if DEBUG - VerifyTaskCompleted(task.IsCompleted); -#endif -#pragma warning disable AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead. - task.GetAwaiter().GetResult(); -#pragma warning restore AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead. - } - - public static T EnsureCompleted(this ValueTask task) - { -#if DEBUG - VerifyTaskCompleted(task.IsCompleted); -#endif -#pragma warning disable AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead. - return task.GetAwaiter().GetResult(); -#pragma warning restore AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead. - } - - public static void EnsureCompleted(this ValueTask task) - { -#if DEBUG - VerifyTaskCompleted(task.IsCompleted); -#endif -#pragma warning disable AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead. - task.GetAwaiter().GetResult(); -#pragma warning restore AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead. - } - - public static Enumerable EnsureSyncEnumerable(this IAsyncEnumerable asyncEnumerable) => new Enumerable(asyncEnumerable); - - public static ConfiguredValueTaskAwaitable EnsureCompleted(this ConfiguredValueTaskAwaitable awaitable, bool async) - { - if (!async) - { -#if DEBUG - VerifyTaskCompleted(awaitable.GetAwaiter().IsCompleted); -#endif - } - return awaitable; - } - - public static ConfiguredValueTaskAwaitable EnsureCompleted(this ConfiguredValueTaskAwaitable awaitable, bool async) - { - if (!async) - { -#if DEBUG - VerifyTaskCompleted(awaitable.GetAwaiter().IsCompleted); -#endif - } - return awaitable; - } - - [Conditional("DEBUG")] - private static void VerifyTaskCompleted(bool isCompleted) - { - if (!isCompleted) - { - if (Debugger.IsAttached) - { - Debugger.Break(); - } - // Throw an InvalidOperationException instead of using - // Debug.Assert because that brings down nUnit immediately - throw new InvalidOperationException("Task is not completed"); - } - } - - /// - /// Both and are defined as public structs so that foreach can use duck typing - /// to call and avoid heap memory allocation. - /// Please don't delete this method and don't make these types private. - /// - /// - public readonly struct Enumerable : IEnumerable - { - private readonly IAsyncEnumerable _asyncEnumerable; - - public Enumerable(IAsyncEnumerable asyncEnumerable) => _asyncEnumerable = asyncEnumerable; - - public Enumerator GetEnumerator() => new Enumerator(_asyncEnumerable.GetAsyncEnumerator()); - - IEnumerator IEnumerable.GetEnumerator() => new Enumerator(_asyncEnumerable.GetAsyncEnumerator()); - - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - } - - public readonly struct Enumerator : IEnumerator - { - private readonly IAsyncEnumerator _asyncEnumerator; - - public Enumerator(IAsyncEnumerator asyncEnumerator) => _asyncEnumerator = asyncEnumerator; - -#pragma warning disable AZC0107 // Do not call public asynchronous method in synchronous scope. - public bool MoveNext() => _asyncEnumerator.MoveNextAsync().EnsureCompleted(); -#pragma warning restore AZC0107 // Do not call public asynchronous method in synchronous scope. - - public void Reset() => throw new NotSupportedException($"{GetType()} is a synchronous wrapper for {_asyncEnumerator.GetType()} async enumerator, which can't be reset, so IEnumerable.Reset() calls aren't supported."); - - public T Current => _asyncEnumerator.Current; - - object IEnumerator.Current => Current; - -#pragma warning disable AZC0107 // Do not call public asynchronous method in synchronous scope. - public void Dispose() => _asyncEnumerator.DisposeAsync().EnsureCompleted(); -#pragma warning restore AZC0107 // Do not call public asynchronous method in synchronous scope. - } - - public readonly struct WithCancellationTaskAwaitable - { - private readonly CancellationToken _cancellationToken; - private readonly ConfiguredTaskAwaitable _awaitable; - - public WithCancellationTaskAwaitable(Task task, CancellationToken cancellationToken) - { - _awaitable = task.ConfigureAwait(false); - _cancellationToken = cancellationToken; - } - - public WithCancellationTaskAwaiter GetAwaiter() => new WithCancellationTaskAwaiter(_awaitable.GetAwaiter(), _cancellationToken); - } - - public readonly struct WithCancellationTaskAwaitable - { - private readonly CancellationToken _cancellationToken; - private readonly ConfiguredTaskAwaitable _awaitable; - - public WithCancellationTaskAwaitable(Task task, CancellationToken cancellationToken) - { - _awaitable = task.ConfigureAwait(false); - _cancellationToken = cancellationToken; - } - - public WithCancellationTaskAwaiter GetAwaiter() => new WithCancellationTaskAwaiter(_awaitable.GetAwaiter(), _cancellationToken); - } - - public readonly struct WithCancellationValueTaskAwaitable - { - private readonly CancellationToken _cancellationToken; - private readonly ConfiguredValueTaskAwaitable _awaitable; - - public WithCancellationValueTaskAwaitable(ValueTask task, CancellationToken cancellationToken) - { - _awaitable = task.ConfigureAwait(false); - _cancellationToken = cancellationToken; - } - - public WithCancellationValueTaskAwaiter GetAwaiter() => new WithCancellationValueTaskAwaiter(_awaitable.GetAwaiter(), _cancellationToken); - } - - public readonly struct WithCancellationTaskAwaiter : ICriticalNotifyCompletion - { - private readonly CancellationToken _cancellationToken; - private readonly ConfiguredTaskAwaitable.ConfiguredTaskAwaiter _taskAwaiter; - - public WithCancellationTaskAwaiter(ConfiguredTaskAwaitable.ConfiguredTaskAwaiter awaiter, CancellationToken cancellationToken) - { - _taskAwaiter = awaiter; - _cancellationToken = cancellationToken; - } - - public bool IsCompleted => _taskAwaiter.IsCompleted || _cancellationToken.IsCancellationRequested; - - public void OnCompleted(Action continuation) => _taskAwaiter.OnCompleted(WrapContinuation(continuation)); - - public void UnsafeOnCompleted(Action continuation) => _taskAwaiter.UnsafeOnCompleted(WrapContinuation(continuation)); - - public void GetResult() - { - Debug.Assert(IsCompleted); - if (!_taskAwaiter.IsCompleted) - { - _cancellationToken.ThrowIfCancellationRequested(); - } - _taskAwaiter.GetResult(); - } - - private Action WrapContinuation(in Action originalContinuation) - => _cancellationToken.CanBeCanceled - ? new WithCancellationContinuationWrapper(originalContinuation, _cancellationToken).Continuation - : originalContinuation; - } - - public readonly struct WithCancellationTaskAwaiter : ICriticalNotifyCompletion - { - private readonly CancellationToken _cancellationToken; - private readonly ConfiguredTaskAwaitable.ConfiguredTaskAwaiter _taskAwaiter; - - public WithCancellationTaskAwaiter(ConfiguredTaskAwaitable.ConfiguredTaskAwaiter awaiter, CancellationToken cancellationToken) - { - _taskAwaiter = awaiter; - _cancellationToken = cancellationToken; - } - - public bool IsCompleted => _taskAwaiter.IsCompleted || _cancellationToken.IsCancellationRequested; - - public void OnCompleted(Action continuation) => _taskAwaiter.OnCompleted(WrapContinuation(continuation)); - - public void UnsafeOnCompleted(Action continuation) => _taskAwaiter.UnsafeOnCompleted(WrapContinuation(continuation)); - - public T GetResult() - { - Debug.Assert(IsCompleted); - if (!_taskAwaiter.IsCompleted) - { - _cancellationToken.ThrowIfCancellationRequested(); - } - return _taskAwaiter.GetResult(); - } - - private Action WrapContinuation(in Action originalContinuation) - => _cancellationToken.CanBeCanceled - ? new WithCancellationContinuationWrapper(originalContinuation, _cancellationToken).Continuation - : originalContinuation; - } - - public readonly struct WithCancellationValueTaskAwaiter : ICriticalNotifyCompletion - { - private readonly CancellationToken _cancellationToken; - private readonly ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter _taskAwaiter; - - public WithCancellationValueTaskAwaiter(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter, CancellationToken cancellationToken) - { - _taskAwaiter = awaiter; - _cancellationToken = cancellationToken; - } - - public bool IsCompleted => _taskAwaiter.IsCompleted || _cancellationToken.IsCancellationRequested; - - public void OnCompleted(Action continuation) => _taskAwaiter.OnCompleted(WrapContinuation(continuation)); - - public void UnsafeOnCompleted(Action continuation) => _taskAwaiter.UnsafeOnCompleted(WrapContinuation(continuation)); - - public T GetResult() - { - Debug.Assert(IsCompleted); - if (!_taskAwaiter.IsCompleted) - { - _cancellationToken.ThrowIfCancellationRequested(); - } - return _taskAwaiter.GetResult(); - } - - private Action WrapContinuation(in Action originalContinuation) - => _cancellationToken.CanBeCanceled - ? new WithCancellationContinuationWrapper(originalContinuation, _cancellationToken).Continuation - : originalContinuation; - } - - private class WithCancellationContinuationWrapper - { - private Action _originalContinuation; - private readonly CancellationTokenRegistration _registration; - - public WithCancellationContinuationWrapper(Action originalContinuation, CancellationToken cancellationToken) - { - Action continuation = ContinuationImplementation; - _originalContinuation = originalContinuation; - _registration = cancellationToken.Register(continuation); - Continuation = continuation; - } - - public Action Continuation { get; } - - private void ContinuationImplementation() - { - Action originalContinuation = Interlocked.Exchange(ref _originalContinuation, null); - if (originalContinuation != null) - { - _registration.Dispose(); - originalContinuation(); - } - } - } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/TypeFormatters.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/TypeFormatters.cs deleted file mode 100644 index 6bb51d611c..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/TypeFormatters.cs +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Xml; - -namespace Azure.Core -{ - internal class TypeFormatters - { - private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; - public static string DefaultNumberFormat { get; } = "G"; - - public static string ToString(bool value) => value ? "true" : "false"; - - public static string ToString(DateTime value, string format) => value.Kind switch - { - DateTimeKind.Utc => ToString((DateTimeOffset)value, format), - _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Azure SDK requires it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") - }; - - public static string ToString(DateTimeOffset value, string format) => format switch - { - "D" => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), - "U" => value.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), - "O" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), - "o" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), - "R" => value.ToString("r", CultureInfo.InvariantCulture), - _ => value.ToString(format, CultureInfo.InvariantCulture) - }; - - public static string ToString(TimeSpan value, string format) => format switch - { - "P" => XmlConvert.ToString(value), - _ => value.ToString(format, CultureInfo.InvariantCulture) - }; - - public static string ToString(byte[] value, string format) => format switch - { - "U" => ToBase64UrlString(value), - "D" => Convert.ToBase64String(value), - _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) - }; - - public static string ToBase64UrlString(byte[] value) - { - var numWholeOrPartialInputBlocks = checked(value.Length + 2) / 3; - var size = checked(numWholeOrPartialInputBlocks * 4); - var output = new char[size]; - - var numBase64Chars = Convert.ToBase64CharArray(value, 0, value.Length, output, 0); - - // Fix up '+' -> '-' and '/' -> '_'. Drop padding characters. - int i = 0; - for (; i < numBase64Chars; i++) - { - var ch = output[i]; - if (ch == '+') - { - output[i] = '-'; - } - else if (ch == '/') - { - output[i] = '_'; - } - else if (ch == '=') - { - // We've reached a padding character; truncate the remainder. - break; - } - } - - return new string(output, 0, i); - } - - public static byte[] FromBase64UrlString(string value) - { - var paddingCharsToAdd = GetNumBase64PaddingCharsToAddForDecode(value.Length); - - var output = new char[value.Length + paddingCharsToAdd]; - - int i; - for (i = 0; i < value.Length; i++) - { - var ch = value[i]; - if (ch == '-') - { - output[i] = '+'; - } - else if (ch == '_') - { - output[i] = '/'; - } - else - { - output[i] = ch; - } - } - - for (; i < output.Length; i++) - { - output[i] = '='; - } - - return Convert.FromBase64CharArray(output, 0, output.Length); - } - - private static int GetNumBase64PaddingCharsToAddForDecode(int inputLength) - { - switch (inputLength % 4) - { - case 0: - return 0; - case 2: - return 2; - case 3: - return 1; - default: - throw new InvalidOperationException("Malformed input"); - } - } - - public static DateTimeOffset ParseDateTimeOffset(string value, string format) - { - return format switch - { - "U" => DateTimeOffset.FromUnixTimeSeconds(long.Parse(value, CultureInfo.InvariantCulture)), - _ => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) - }; - } - - public static TimeSpan ParseTimeSpan(string value, string format) => format switch - { - "P" => XmlConvert.ToTimeSpan(value), - _ => TimeSpan.ParseExact(value, format, CultureInfo.InvariantCulture) - }; - - public static string ConvertToString(object? value, string? format = null) - => value switch - { - null => "null", - string s => s, - bool b => ToString(b), - int or float or double or long or decimal => ((IFormattable)value).ToString(DefaultNumberFormat, CultureInfo.InvariantCulture), - byte[] b when format != null => ToString(b, format), - IEnumerable s => string.Join(",", s), - DateTimeOffset dateTime when format != null => ToString(dateTime, format), - TimeSpan timeSpan when format != null => ToString(timeSpan, format), - TimeSpan timeSpan => XmlConvert.ToString(timeSpan), - Guid guid => guid.ToString(), - BinaryData binaryData => TypeFormatters.ConvertToString(binaryData.ToArray(), format), - _ => value.ToString()! - }; - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/TypeReferenceTypeAttribute.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/TypeReferenceTypeAttribute.cs deleted file mode 100644 index dce5c4f331..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/TypeReferenceTypeAttribute.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; - -namespace Azure.Core -{ - /// - /// An attribute class indicating to Autorest a reference type which can replace a type in target SDKs. - /// - [AttributeUsage(AttributeTargets.Class)] - internal class TypeReferenceTypeAttribute : Attribute - { - /// - /// Constructs a new instance of . - /// - public TypeReferenceTypeAttribute() - : this(false, Array.Empty()) - { - } - - /// - /// Constructs a new instance of . - /// - /// Whether to allow replacement to occur when the type to be replaced - /// contains extra properties as compared to the reference type attributed with that it will - /// be replaced with. Defaults to false. - /// An array of internal properties to include for the reference type when evaluating whether type - /// replacement should occur. When evaluating a type for replacement with a reference type, all internal properties are considered on the - /// type to be replaced. Thus this parameter can be used to specify internal properties to allow replacement to occur on a type with internal - /// properties. - public TypeReferenceTypeAttribute(bool ignoreExtraProperties, string[] internalPropertiesToInclude) - { - IgnoreExtraProperties = ignoreExtraProperties; - InternalPropertiesToInclude = internalPropertiesToInclude; - } - - public bool IgnoreExtraProperties { get; } - public string[] InternalPropertiesToInclude { get; } - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/VoidValue.cs b/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/VoidValue.cs deleted file mode 100644 index cb52e0eafb..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/Shared/VoidValue.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Text.Json; - -namespace Azure.Core -{ - internal readonly struct VoidValue { } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/autorest.md b/tests/dotnet-upgrade/dotnet-aot-compat/before/autorest.md deleted file mode 100644 index 3735f0952b..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/autorest.md +++ /dev/null @@ -1,839 +0,0 @@ -# Generated code configuration - -Run `dotnet build /t:GenerateCode` to generate code. - -```yaml -azure-arm: true -arm-core: true -clear-output-folder: true -skip-csproj: true -model-namespace: false -public-clients: false -head-as-boolean: false -modelerfour: - lenient-model-deduplication: true -use-model-reader-writer: true -deserialize-null-collection-as-null-value: true -enable-bicep-serialization: true - -#mgmt-debug: -# show-serialized-names: true - -batch: - - tag: package-common-type - - tag: package-resources - - tag: package-management -``` - -### Tag: package-common-type - -These settings apply only when `--tag=package-common-type` is specified on the command line. - -``` yaml $(tag) == 'package-common-type' -output-folder: $(this-folder)/Common/Generated -sample-gen: - output-folder: $(this-folder)/../samples/Generated - clear-output-folder: true -namespace: Azure.ResourceManager -input-file: - - https://github.com/Azure/azure-rest-api-specs/blob/78eac0bd58633028293cb1ec1709baa200bed9e2/specification/common-types/resource-management/v3/types.json - - https://github.com/Azure/azure-rest-api-specs/blob/78eac0bd58633028293cb1ec1709baa200bed9e2/specification/common-types/resource-management/v4/managedidentity.json - -format-by-name-rules: - 'tenantId': 'uuid' - 'etag': 'etag' - 'location': 'azure-location' - '*Uri': 'Uri' - '*Uris': 'Uri' - -acronym-mapping: - CPU: Cpu - CPUs: Cpus - Os: OS - Ip: IP - Ips: IPs - ID: Id - IDs: Ids - VM: Vm - VMs: Vms - Vmos: VmOS - VMScaleSet: VmScaleSet - DNS: Dns - VPN: Vpn - NAT: Nat - WAN: Wan - Ipv4: IPv4 - Ipv6: IPv6 - Ipsec: IPsec - SSO: Sso - URI: Uri - -directive: - - from: types.json - where: $.definitions.Resource - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-ms-client-name"] = "ResourceData"; - $["x-accessibility"] = "public"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; - - from: types.json - where: $.definitions.TrackedResource - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-ms-client-name"] = "TrackedResourceData"; - $["x-accessibility"] = "public"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; - - from: types.json - where: $.definitions.Plan - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-accessibility"] = "public"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; - - from: types.json - where: $.definitions.Sku - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-accessibility"] = "public"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; - - from: types.json - where: $.definitions.systemData - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-accessibility"] = "public"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; -# Workaround for the issue that SystemData lost readonly attribute: https://github.com/Azure/autorest/issues/4269 - - from: types.json - where: $.definitions.systemData.properties.* - transform: > - $["readOnly"] = true; - - from: types.json - where: $.definitions.encryptionProperties - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-accessibility"] = "public"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; - - from: types.json - where: $.definitions.KeyVaultProperties - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-accessibility"] = "public"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; - - from: types.json - where: $.definitions.*.properties[?(@.enum)] - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-accessibility"] = "public"; - - from: types.json - where: $.definitions.OperationStatusResult - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; - - from: types.json - where: $.definitions.OperationStatusResult.properties.* - transform: > - $["readOnly"] = true; - - from: managedidentity.json - where: $.definitions.SystemAssignedServiceIdentity - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-accessibility"] = "public"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; - $.properties.type["x-ms-client-name"] = "SystemAssignedServiceIdentityType"; - - from: managedidentity.json - where: $.definitions.UserAssignedIdentity - transform: > - $["x-namespace"] = "Azure.ResourceManager.Models"; - $["x-accessibility"] = "public"; - $["x-csharp-formats"] = "json"; - $["x-csharp-usage"] = "model,input,output"; -``` - -### Tag: package-resources - -These settings apply only when `--tag=package-resources` is specified on the command line. - -``` yaml $(tag) == 'package-resources' -output-folder: $(this-folder)/Resources/Generated -sample-gen: - output-folder: $(this-folder)/../samples/Generated - clear-output-folder: false -namespace: Azure.ResourceManager.Resources -title: ResourceManagementClient -input-file: - - https://github.com/Azure/azure-rest-api-specs/blob/817861452040bf29d14b57ac7418560e4680e06e/specification/resources/resource-manager/Microsoft.Authorization/stable/2022-06-01/policyAssignments.json - - https://github.com/Azure/azure-rest-api-specs/blob/90a65cb3135d42438a381eb8bb5461a2b99b199f/specification/resources/resource-manager/Microsoft.Authorization/stable/2021-06-01/policyDefinitions.json - - https://github.com/Azure/azure-rest-api-specs/blob/90a65cb3135d42438a381eb8bb5461a2b99b199f/specification/resources/resource-manager/Microsoft.Authorization/stable/2021-06-01/policySetDefinitions.json - - https://github.com/Azure/azure-rest-api-specs/blob/78eac0bd58633028293cb1ec1709baa200bed9e2/specification/resources/resource-manager/Microsoft.Authorization/stable/2020-09-01/dataPolicyManifests.json - - https://github.com/Azure/azure-rest-api-specs/blob/78eac0bd58633028293cb1ec1709baa200bed9e2/specification/resources/resource-manager/Microsoft.Authorization/stable/2020-05-01/locks.json - - https://github.com/Azure/azure-rest-api-specs/blob/90a65cb3135d42438a381eb8bb5461a2b99b199f/specification/resources/resource-manager/Microsoft.Resources/stable/2022-09-01/resources.json - - https://github.com/Azure/azure-rest-api-specs/blob/78eac0bd58633028293cb1ec1709baa200bed9e2/specification/resources/resource-manager/Microsoft.Resources/stable/2022-12-01/subscriptions.json - - https://github.com/Azure/azure-rest-api-specs/blob/78eac0bd58633028293cb1ec1709baa200bed9e2/specification/resources/resource-manager/Microsoft.Features/stable/2021-07-01/features.json - -list-exception: - - /{resourceId} - -request-path-to-resource-data: - # subscription does not have name and type - /subscriptions/{subscriptionId}: Subscription - # tenant does not have name and type - /: Tenant - # provider does not have name and type - /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}: ResourceProvider - -request-path-is-non-resource: - - /subscriptions/{subscriptionId}/locations - -request-path-to-parent: - /subscriptions: /subscriptions/{subscriptionId} - /tenants: / - /subscriptions/{subscriptionId}/locations: /subscriptions/{subscriptionId} - /subscriptions/{subscriptionId}/providers: /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}: /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - -request-path-to-resource-type: - /subscriptions/{subscriptionId}/locations: Microsoft.Resources/locations - /tenants: Microsoft.Resources/tenants - /: Microsoft.Resources/tenants - /subscriptions: Microsoft.Resources/subscriptions - /subscriptions/{subscriptionId}/resourcegroups: Microsoft.Resources/resourceGroups - /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}: Microsoft.Resources/features - /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}: Microsoft.Resources/providers - /providers: Microsoft.Resources/providers - -request-path-to-scope-resource-types: - /{scope}/providers/Microsoft.Authorization/locks/{lockName}: - - subscriptions - - resourceGroups - - "*" -operation-positions: - CheckResourceName: collection - -operation-groups-to-omit: - - Deployments - - DeploymentOperations - - AuthorizationOperations - -override-operation-name: - Tags_List: GetAllPredefinedTags - Tags_DeleteValue: DeletePredefinedTagValue - Tags_CreateOrUpdateValue: CreateOrUpdatePredefinedTagValue - Tags_CreateOrUpdate: CreateOrUpdatePredefinedTag - Tags_Delete: DeletePredefinedTag - Providers_ListAtTenantScope: GetTenantResourceProviders - Providers_GetAtTenantScope: GetTenantResourceProvider - Resources_List: GetGenericResources - Resources_ListByResourceGroup: GetGenericResources - Resources_MoveResources: MoveResources - Resources_ValidateMoveResources: ValidateMoveResources - -no-property-type-replacement: ResourceProviderData;ResourceProvider - -operations-to-skip-lro-api-version-override: -- Tags_CreateOrUpdateAtScope -- Tags_UpdateAtScope -- Tags_DeleteAtScope - -generate-arm-resource-extensions: -- /{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName} -- /{scope}/providers/Microsoft.Authorization/locks/{lockName} - -format-by-name-rules: - 'tenantId': 'uuid' - 'etag': 'etag' - 'location': 'azure-location' - '*Uri': 'Uri' - '*Uris': 'Uri' - -keep-plural-enums: - - ResourceTypeAliasPathAttributes - -acronym-mapping: - CPU: Cpu - CPUs: Cpus - Os: OS - Ip: IP - Ips: IPs - ID: Id - IDs: Ids - VM: Vm - VMs: Vms - Vmos: VmOS - VMScaleSet: VmScaleSet - DNS: Dns - VPN: Vpn - NAT: Nat - WAN: Wan - Ipv4: IPv4 - Ipv6: IPv6 - Ipsec: IPsec - SSO: Sso - URI: Uri - -rename-mapping: - PolicyAssignment.identity: ManagedIdentity - Override: PolicyOverride - OverrideKind: PolicyOverrideKind - Selector: ResourceSelectorExpression - SelectorKind: ResourceSelectorKind - Location: LocationExpanded - ResourcesMoveContent.targetResourceGroup: targetResourceGroupId|arm-id - LocationMetadata.pairedRegion: PairedRegions - CheckResourceNameResult: ResourceNameValidationResult - CheckResourceNameResult.type: ResourceType|resource-type - ResourceName: ResourceNameValidationContent - ResourceName.type: ResourceType|resource-type - ResourceNameStatus: ResourceNameValidationStatus - Resource: ResourceData - TrackedResource: TrackedResourceData - -directive: - # These methods can be replaced by using other methods in the same operation group, remove for Preview. - - remove-operation: PolicyAssignments_UpdateById - - remove-operation: PolicyAssignments_DeleteById - - remove-operation: PolicyAssignments_CreateById - - remove-operation: PolicyAssignments_GetById - - remove-operation: ManagementLocks_CreateOrUpdateAtResourceGroupLevel - - remove-operation: ManagementLocks_CreateOrUpdateAtResourceLevel - - remove-operation: ManagementLocks_CreateOrUpdateAtSubscriptionLevel - - remove-operation: ManagementLocks_DeleteAtResourceGroupLevel - - remove-operation: ManagementLocks_DeleteAtResourceLevel - - remove-operation: ManagementLocks_DeleteAtSubscriptionLevel - - remove-operation: ManagementLocks_GetAtResourceGroupLevel - - remove-operation: ManagementLocks_GetAtResourceLevel - - remove-operation: ManagementLocks_GetAtSubscriptionLevel - - remove-operation: ManagementLocks_ListAtResourceGroupLevel - - remove-operation: ManagementLocks_ListAtResourceLevel - - remove-operation: ManagementLocks_ListAtSubscriptionLevel - # These methods was not in the previous manual code, remove them for the first generation and can add them back later. - - remove-operation: ResourceGroups_CheckExistence - - remove-operation: Resources_CheckExistenceById - - remove-operation: Resources_CheckExistence - - remove-operation: Resources_CreateOrUpdate - - remove-operation: Resources_Update - - remove-operation: Resources_Get - - remove-operation: Resources_Delete - - remove-operation: Providers_RegisterAtManagementGroupScope - - remove-operation: Subscriptions_CheckZonePeers - - remove-operation: AuthorizationOperations_List - # Deduplicate - - from: subscriptions.json - where: '$.paths["/providers/Microsoft.Resources/operations"].get' - transform: > - $["operationId"] = "Operations_ListSubscriptionOperations"; - reason: Rename duplicate operation Id. - - from: resources.json - where: '$.paths["/providers/Microsoft.Resources/operations"].get' - transform: > - $["operationId"] = "Operations_ListResourcesOperations"; - reason: Rename duplicate operation Id. - - from: features.json - where: '$.paths["/providers/Microsoft.Features/operations"].get' - transform: > - $["operationId"] = "Operations_ListFeaturesOperations"; - reason: Add operation group so that we can omit related models by the operation group. - - from: links.json - where: $.definitions - transform: > - $["OperationListResult"]["x-ms-client-name"] = "ResourceLinkOperationListResult"; - $["Operation"]["x-ms-client-name"] = "ResourceLinksOperation"; - - from: subscriptions.json - where: $.definitions - transform: > - $["OperationListResult"] = undefined; - $["Operation"] = undefined; - - from: features.json - where: $.definitions - transform: > - $["OperationListResult"]["x-ms-client-name"] = "FeatureOperationListResult"; - $["Operation"]["x-ms-client-name"] = "FeatureOperation"; - $["Operation"]["properties"]["displayOfFeature"] = $["Operation"]["properties"]["display"]; - $["Operation"]["properties"]["display"] = undefined; - - from: features.json - where: $.definitions.ErrorResponse - transform: > - $["x-ms-client-name"] = "FeatureErrorResponse"; - # remove the systemData property because we already included this property in its base class and the type replacement somehow does not work in resourcemanager - - from: policyAssignments.json - where: $.definitions.PolicyAssignment.properties.systemData - transform: return undefined; - - from: policyDefinitions.json - where: $.definitions.PolicyDefinition.properties.systemData - transform: return undefined; - - from: policySetDefinitions.json - where: $.definitions.PolicySetDefinition.properties.systemData - transform: return undefined; - - from: resources.json - where: $.definitions.ExtendedLocation - transform: > - $["x-namespace"] = "Azure.ResourceManager.Resources.Models"; - - - rename-model: - from: Provider - to: ResourceProvider - - rename-model: - from: ProviderListResult - to: ResourceProviderListResult - - rename-model: - from: TenantIdDescription - to: Tenant - - rename-model: - from: Tags - to: Tag - - rename-model: - from: TagsResource - to: TagResource - - rename-model: - from: TagsPatchResource - to: TagPatchResource - - rename-model: - from: TagCount - to: PredefinedTagCount - - rename-model: - from: TagValue - to: PredefinedTagValue - - rename-model: - from: TagDetails - to: PredefinedTag - - rename-model: - from: TagsListResult - to: PredefinedTagsListResult - - rename-model: - from: FeatureResult - to: Feature - - rename-model: - from: Resource - to: TrackedResourceExtendedData - - rename-model: - from: ResourcesMoveInfo - to: ResourcesMoveContent - - from: resources.json - where: $.definitions.Provider - transform: - $["x-ms-client-name"] = "ResourceProvider"; - - from: resources.json - where: $.definitions.Alias - transform: - $["x-ms-client-name"] = "ResourceTypeAlias"; - - from: resources.json - where: $.definitions.AliasPath - transform: - $["x-ms-client-name"] = "ResourceTypeAliasPath"; - - from: resources.json - where: $.definitions.AliasPathMetadata.properties.attributes["x-ms-enum"] - transform: - $["name"] = "ResourceTypeAliasPathAttributes"; - - from: resources.json - where: $.definitions.AliasPathMetadata - transform: - $["x-ms-client-name"] = "ResourceTypeAliasPathMetadata"; - - from: resources.json - where: $.definitions.AliasPathMetadata.properties.type["x-ms-enum"] - transform: - $["name"] = "ResourceTypeAliasPathTokenType"; - - from: resources.json - where: $.definitions.AliasPattern - transform: - $["x-ms-client-name"] = "ResourceTypeAliasPattern"; - - from: resources.json - where: $.definitions.AliasPattern.properties.type["x-ms-enum"] - transform: - $["name"] = "ResourceTypeAliasPatternType"; - - from: resources.json - where: $.definitions.Alias.properties.type["x-ms-enum"] - transform: - $["name"] = "ResourceTypeAliasType"; - - from: policyDefinitions.json - where: $.definitions.ParameterDefinitionsValue - transform: - $["x-ms-client-name"] = "ArmPolicyParameter"; - - from: policyDefinitions.json - where: $.definitions.ParameterDefinitionsValue.properties.type["x-ms-enum"] - transform: - $["name"] = "ArmPolicyParameterType"; - - from: policyAssignments.json - where: $.definitions.ParameterValuesValue - transform: - $["x-ms-client-name"] = "ArmPolicyParameterValue"; - - remove-model: DeploymentExtendedFilter - - remove-model: ResourceProviderOperationDisplayProperties - - from: subscriptions.json - where: $.paths - transform: > - $["/"] = { - "get": { - "tags": [ - "Tenants" - ], - "operationId": "Tenants_Get", - "description": "Gets details about the default tenant.", - "parameters": [ - { - "$ref": "../../../../../common-types/resource-management/v5/types.json#/parameters/ApiVersionParameter" - } - ], - "responses": { - "200": { - "description": "OK - Returns information about the tenant.", - "schema": { - "$ref": "#/definitions/Tenant" - } - }, - "default": { - "description": "Error response describing why the operation failed.", - "schema": { - "$ref": "#/definitions/CloudError" - } - } - } - } - } - reason: add a fake tenant get operation so that we can generate a tenant where all the Get[TenantResources] operations can be autogen in it. The get operation will be removed with codegen suppress attributes. - - - from: resources.json - where: $.definitions - transform: > - $["TenantResourceProvider"] = { - "properties": { - "namespace": { - "type": "string", - "description": "The namespace of the resource provider." - }, - "resourceTypes": { - "readOnly": true, - "type": "array", - "items": { - "$ref": "#/definitions/ProviderResourceType" - }, - "description": "The collection of provider resource types." - } - }, - "description": "Resource provider information." - } - reason: This is the real response for a tenant provider. - - from: resources.json - where: $.definitions - transform: > - $["TenantResourceProviderListResult"] = { - "properties": { - "value": { - "type": "array", - "items": { - "$ref": "#/definitions/TenantResourceProvider" - }, - "description": "An array of resource providers." - }, - "nextLink": { - "readOnly": true, - "type": "string", - "description": "The URL to use for getting the next set of results." - } - }, - "description": "List of resource providers." - } - - from: resources.json - where: $.definitions.TenantResourceProviderListResult.properties.value.items["$ref"] - transform: return "#/definitions/TenantResourceProvider" - - from: resources.json - where: $.paths["/providers"].get.responses["200"].schema["$ref"] - transform: return "#/definitions/TenantResourceProviderListResult" - - from: resources.json - where: $.paths["/providers/{resourceProviderNamespace}"].get.responses["200"].schema["$ref"] - transform: return "#/definitions/TenantResourceProvider" - - - from: resources.json - where: $.definitions.Identity.properties.type["x-ms-enum"] - transform: > - $["name"] = "GenericResourceIdentityType"; - $["modelAsString"] = true; - - from: resources.json - where: $.definitions.Identity - transform: > - $["required"] = ["type"] - - from: resources.json - where: $.definitions.Identity - transform: > - $["x-ms-client-name"] = "GenericResourceIdentity"; - - from: policyAssignments.json - where: $.definitions.Identity.properties.type["x-ms-enum"] - transform: $["name"] = "PolicyAssignmentIdentityType" - - from: policyAssignments.json - where: $.definitions.Identity - transform: > - $["x-ms-client-name"] = "PolicyAssignmentIdentity"; - - from: locks.json - where: $.paths..parameters[?(@.name === "scope")] - transform: > - $["x-ms-skip-url-encoding"] = true - # Rename GenericResourceExpanded to GenericResource and use it as the schema for both single resource operation and collection operation. - - from: resources.json - where: $.definitions.ResourceListResult.properties.value.items["$ref"] - transform: > - $ = "#/definitions/GenericResource" - - from: resources.json - where: $.definitions - transform: > - $.GenericResource.properties["createdTime"] = $.GenericResourceExpanded.properties["createdTime"]; - $.GenericResource.properties["changedTime"] = $.GenericResourceExpanded.properties["changedTime"]; - $.GenericResource.properties["provisioningState"] = $.GenericResourceExpanded.properties["provisioningState"]; - delete $.GenericResourceExpanded; - - from: locks.json - where: $.definitions.ManagementLockObject - transform: $["x-ms-client-name"] = "ManagementLock" - - from: links.json - where: $.definitions.ResourceLink.properties.type - transform: > - $["x-ms-client-name"] = "ResourceType"; - $["type"] = "string"; - - from: dataPolicyManifests.json - where: $.definitions.DataEffect - transform: > - $["x-ms-client-name"] = "DataPolicyManifestEffect"; - - from: locks.json - where: $.definitions.ManagementLockProperties.properties.level["x-ms-enum"] - transform: > - $["name"] = "ManagementLockLevel" - - from: subscriptions.json - where: $.definitions.Subscription.properties.tenantId - transform: > - $['format'] = "uuid" - - from: subscriptions.json - where: $.definitions.Tenant.properties.tenantId - transform: > - $['format'] = "uuid" - - from: subscriptions.json - where: $.definitions.ManagedByTenant.properties.tenantId - transform: > - $['format'] = "uuid" - - from: resources.json - where: $.definitions.ResourcesMoveInfo.properties.resources.items - transform: > - $["x-ms-format"] = "arm-id" - - from: resources.json - where: $.definitions.RoleDefinition - transform: > - $["x-ms-client-name"] = "AzureRoleDefinition"; - - from: resources.json - where: $.definitions.TagPatchResource.properties.operation["x-ms-enum"] - transform: > - $["name"] = "TagPatchMode" - - from: resources.json - where: $.definitions.TagPatchResource.properties.operation - transform: > - $["x-ms-client-name"] = "PatchMode" - - from: dataPolicyManifests.json - where: $.definitions.DataManifestResourceFunctionsDefinition.properties.custom - transform: > - $["x-ms-client-name"] = "CustomDefinitions" - - from: policyAssignments.json - where: $.definitions.PolicyAssignmentProperties.properties.notScopes - transform: > - $["x-ms-client-name"] = "ExcludedScopes" - - from: resources.json - where: $.definitions.ExportTemplateRequest - transform: > - $["x-ms-client-name"] = "ExportTemplate" - - from: dataPolicyManifests.json - where: $.definitions.DataManifestCustomResourceFunctionDefinition.properties.fullyQualifiedResourceType - transform: > - $["x-ms-format"] = "resource-type" - - from: resources.json - where: $.definitions.Permission.properties.actions - transform: > - $["x-ms-client-name"] = "AllowedActions" - - from: resources.json - where: $.definitions.Permission.properties.notActions - transform: > - $["x-ms-client-name"] = "DeniedActions" - - from: resources.json - where: $.definitions.Permission.properties.dataActions - transform: > - $["x-ms-client-name"] = "AllowedDataActions" - - from: resources.json - where: $.definitions.Permission.properties.notDataActions - transform: > - $["x-ms-client-name"] = "DeniedDataActions" - - from: policyAssignments.json - where: $.definitions.PolicyAssignment.properties.location - transform: > - $["x-ms-format"] = "azure-location" - - from: resources.json - where: $.definitions.ProviderExtendedLocation.properties.location - transform: > - $["x-ms-format"] = "azure-location" -``` - -### Tag: package-management - -These settings apply only when `--tag=package-management` is specified on the command line. - -``` yaml $(tag) == 'package-management' -output-folder: $(this-folder)/ManagementGroup/Generated -sample-gen: - output-folder: $(this-folder)/../samples/Generated - clear-output-folder: false -namespace: Azure.ResourceManager.ManagementGroups -title: ManagementClient -input-file: - - https://github.com/Azure/azure-rest-api-specs/blob/90a65cb3135d42438a381eb8bb5461a2b99b199f/specification/managementgroups/resource-manager/Microsoft.Management/stable/2021-04-01/management.json -request-path-to-parent: - /providers/Microsoft.Management/checkNameAvailability: /providers/Microsoft.Management/managementGroups/{groupId} - /providers/Microsoft.Management/getEntities: /providers/Microsoft.Management/managementGroups/{groupId} -operation-positions: - ManagementGroups_CheckNameAvailability: collection - Entities_List: collection -operation-groups-to-omit: - - HierarchySettings - - TenantBackfill -no-property-type-replacement: DescendantParentGroupInfo - -format-by-name-rules: - 'tenantId': 'uuid' - 'etag': 'etag' - 'location': 'azure-location' - '*Uri': 'Uri' - '*Uris': 'Uri' - -rename-mapping: - EntityInfo: EntityData - Permissions: EntityPermission - Permissions.noaccess: NoAccess - SearchOptions: EntitySearchOption - SubscriptionUnderManagementGroup: ManagementGroupSubscription - -override-operation-name: - ManagementGroupSubscriptions_GetSubscription: GetManagementGroupSubscription - -acronym-mapping: - CPU: Cpu - CPUs: Cpus - Os: OS - Ip: IP - Ips: IPs - ID: Id - IDs: Ids - VM: Vm - VMs: Vms - Vmos: VmOS - VMScaleSet: VmScaleSet - DNS: Dns - VPN: Vpn - NAT: Nat - WAN: Wan - Ipv4: IPv4 - Ipv6: IPv6 - Ipsec: IPsec - SSO: Sso - URI: Uri -directive: - - rename-model: - from: CreateManagementGroupChildInfo - to: ManagementGroupChildOptions - - rename-model: - from: CreateParentGroupInfo - to: ManagementGroupParentCreateOptions - - rename-operation: - from: CheckNameAvailability - to: ManagementGroups_CheckNameAvailability - - rename-operation: - from: StartTenantBackfill - to: TenantBackfill_Start - - rename-operation: - from: TenantBackfillStatus - to: TenantBackfill_Status - - from: management.json - where: $.parameters.SkipTokenParameter - transform: > - $['x-ms-client-name'] = 'SkipToken' - - from: management.json - where: $.parameters.ExpandParameter - transform: > - $['x-ms-enum'] = { - name: "ManagementGroupExpandType", - modelAsString: true - } - - from: management.json - where: $.definitions.ManagementGroupListResult.properties.value.items - transform: > - $['$ref'] = "#/definitions/ManagementGroup" - - from: management.json - where: $.definitions.ManagementGroupInfo - transform: 'return undefined' - - remove-model: OperationResults - - from: management.json - where: $.definitions.CheckNameAvailabilityResult.properties.reason - transform: > - $['x-ms-enum'] = { - name: "ManagementGroupNameUnavailableReason" - } - - from: management.json - where: $.definitions.ManagementGroupChildType - transform: > - $['x-ms-enum'].modelAsString = true - - from: management.json - where: $.definitions.CheckNameAvailabilityResult - transform: > - $['x-ms-client-name'] = "ManagementGroupNameAvailabilityResult" - - from: management.json - where: $.parameters.SearchParameter - transform: > - $['x-ms-enum'] = { - name: "SearchOptions", - modelAsString: true - } - reason: omit operation group does not clean this enum parameter, rename it and then suppress with codegen attribute. - - from: management.json - where: $.parameters.EntityViewParameter - transform: > - $['x-ms-enum'] = { - name: "EntityViewOptions", - modelAsString: true - } - reason: omit operation group does not clean this enum parameter, rename it and then suppress with codegen attribute. - - remove-model: EntityHierarchyItem - - remove-model: EntityHierarchyItemProperties - - from: management.json - where: $.definitions.CreateManagementGroupProperties.properties.tenantId - transform: > - $['format'] = "uuid" - - from: management.json - where: $.definitions.DescendantInfo - transform: > - $['x-ms-client-name'] = "DescendantData" - - from: management.json - where: $.definitions.DescendantParentGroupInfo.properties.id - transform: > - $["x-ms-format"] = "arm-id" - - from: management.json - where: $.definitions.ManagementGroupDetails.properties.managementGroupAncestorsChain - transform: > - $["x-ms-client-name"] = "managementGroupAncestorChain" - - from: management.json - where: $.definitions.ManagementGroupDetails - transform: > - $["x-ms-client-name"] = "ManagementGroupInfo" - - from: management.json - where: $.definitions.ParentGroupInfo - transform: > - $["x-ms-client-name"] = "ParentManagementGroupInfo" - - from: management.json - where: $.definitions.ManagementGroupProperties.properties.tenantId - transform: > - $['format'] = "uuid" - - from: management.json - where: $.definitions - transform: > - $.CreateManagementGroupRequest.properties.type['x-ms-format'] = 'resource-type'; - $.CheckNameAvailabilityRequest["x-ms-client-name"] = "ManagementGroupNameAvailabilityContent"; - $.CheckNameAvailabilityRequest.properties.type['x-ms-client-name'] = "ResourceType"; - $.CheckNameAvailabilityRequest.properties.type['x-ms-constant'] = true; - $.CheckNameAvailabilityRequest.properties.type['x-ms-format'] = 'resource-type'; -``` diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/before/global.json b/tests/dotnet-upgrade/dotnet-aot-compat/before/global.json deleted file mode 100644 index 3be1c15acd..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/before/global.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "sdk": { - "version": "9.0.300", - "rollForward": "latestFeature" - } -} diff --git a/tests/dotnet-upgrade/dotnet-aot-compat/eval.yaml b/tests/dotnet-upgrade/dotnet-aot-compat/eval.yaml deleted file mode 100644 index 13723fa5d5..0000000000 --- a/tests/dotnet-upgrade/dotnet-aot-compat/eval.yaml +++ /dev/null @@ -1,33 +0,0 @@ -name: dotnet-aot-compat -description: Evaluates the dotnet-upgrade/dotnet-aot-compat skill -type: capability -config: - timeout: 1050s -stimuli: - - name: Make Azure.ResourceManager AOT-compatible - prompt: Make the project in the before/ directory AOT-compatible. Do not consult the after/ directory. - environment: - files: - - src: . - dest: . - graders: - - type: file-contains - config: - path: before/Azure.ResourceManager.csproj - value: IsAotCompatible - - type: prompt - rubric: - - Added IsAotCompatible to the .csproj - - Built with AOT/trim analyzers enabled and identified IL warnings - - Used DynamicallyAccessedMembers annotations to preserve annotation flow where possible - - Used RequiresUnreferencedCode only as a last resort for fundamentally reflection-dependent code - - "Did NOT use #pragma warning disable or UnconditionalSuppressMessage for any IL warning. Warnings hidden via - suppression do not count as resolved." - - Iteratively rebuilt to verify warnings were resolved, working from innermost call sites outward - - Used source-generated System.Text.Json instead of reflection-based JSON serialization - - "Final build produces 0 IL warnings. Warnings suppressed via #pragma or [UnconditionalSuppressMessage] still - count as unresolved." - constraints: - expect_tools: - - bash - - dotnet diff --git a/tests/dotnet-upgrade/migrate-dotnet9-to-dotnet10/eval.yaml b/tests/dotnet-upgrade/migrate-dotnet9-to-dotnet10/eval.yaml deleted file mode 100644 index 63362cfe95..0000000000 --- a/tests/dotnet-upgrade/migrate-dotnet9-to-dotnet10/eval.yaml +++ /dev/null @@ -1,767 +0,0 @@ -name: migrate-dotnet9-to-dotnet10 -description: Evaluates the dotnet-upgrade/migrate-dotnet9-to-dotnet10 skill -type: capability -config: - timeout: 4m -stimuli: - - name: Console app with System.Linq.Async, SIGTERM, and BufferedStream - prompt: > - I have a .NET 9 console app (no Generic Host) that: - - - References System.Linq.Async 6.0.1 for IAsyncEnumerable LINQ queries - - - Uses AppDomain.ProcessExit to flush logs and clean up when SIGTERM is received in Docker - - - Has a custom stream pipeline that writes byte-by-byte to a BufferedStream and expects automatic flushing when - the buffer fills - - - Uses DistributedContextPropagator for trace context propagation in a custom format (not W3C) - - What breaks when migrating to .NET 10? - graders: - - type: output-matches - config: - pattern: (System\.Linq\.Async|AsyncEnumerable) - - type: output-matches - config: - pattern: (SIGTERM|PosixSignal|signal|ProcessExit) - - type: output-matches - config: - pattern: (BufferedStream|WriteByte|[Ff]lush) - - type: prompt - rubric: - - Identifies System.Linq.Async conflict with built-in AsyncEnumerable; recommends removing the package, upgrading - to v7, or using ExcludeAssets - - Explains the runtime no longer registers SIGTERM handlers, so AppDomain.ProcessExit won't fire; recommends - PosixSignalRegistration.Create - - Warns that BufferedStream.WriteByte no longer implicitly flushes and recommends adding explicit Flush() calls - - Mentions the default trace context propagator changed to W3C standard - - name: Expression tree code broken by C# 14 span overload resolution - prompt: | - I'm migrating a .NET 9 library to .NET 10. It builds LINQ expression trees that call .Contains() on int[] arrays: - ```csharp - Expression> expr = (array, num) => array.Contains(num); - expr.Compile(preferInterpretation: true)(new[] { 1, 2, 3 }, 2); - ``` - After upgrading to .NET 10 / C# 14, this throws at runtime. What happened and how do I fix it? - graders: - - type: output-matches - config: - pattern: (span|Span|MemoryExtensions|overload) - - type: output-matches - config: - pattern: (IEnumerable|AsEnumerable|Enumerable\.Contains) - - type: prompt - rubric: - - Explains that C# 14 span conversions cause MemoryExtensions.Contains to bind instead of Enumerable.Contains for - array.Contains() in expressions - - "Provides at least one concrete fix: casting to IEnumerable, using .AsEnumerable(), or calling - Enumerable.Contains explicitly" - - name: ASP.NET Core app with WebHostBuilder, OpenAPI, and forwarded headers - prompt: | - I'm upgrading a .NET 9 ASP.NET Core web API. The codebase: - - Uses WebHostBuilder in Program.cs (the legacy hosting model) - - Calls .WithOpenApi() on minimal API endpoints - - Has true in the csproj - - References Microsoft.Extensions.ApiDescription.Client for NSwag code generation - - Uses IActionContextAccessor registered as a singleton - - Uses IPNetwork in ForwardedHeadersOptions.KnownNetworks - - Uses AddRazorRuntimeCompilation() for dev-time Razor editing - - Has API endpoints that currently get redirected to the login page on 401 - What needs to change for .NET 10? - graders: - - type: output-matches - config: - pattern: (WebHostBuilder|obsolete|WebApplication) - - type: output-matches - config: - pattern: (WithOpenApi|deprecated|OpenAPI) - - type: output-matches - config: - pattern: (IActionContextAccessor|obsolete) - - type: prompt - rubric: - - Identifies WebHostBuilder/IWebHost/WebHost as obsolete; recommends WebApplication.CreateBuilder - - Notes WithOpenApi() is deprecated - - Notes IncludeOpenAPIAnalyzers property is deprecated and should be removed - - Notes Microsoft.Extensions.ApiDescription.Client is deprecated - - Identifies IActionContextAccessor as obsolete - - Warns that IPNetwork and ForwardedHeadersOptions.KnownNetworks are obsolete - - Notes Razor runtime compilation is obsolete; suggests dotnet watch / hot reload - - Mentions cookie auth no longer redirects API endpoints to login — now returns 401 directly - - name: ASP.NET Core app with OpenAPI transformers using Microsoft.OpenApi v1 APIs - prompt: > - I'm migrating a .NET 9 ASP.NET Core web API to .NET 10. We have custom OpenAPI transformers that manipulate the - document. After upgrading Microsoft.AspNetCore.OpenApi to 10.0, we get compilation errors. Here's our code: - - - ```csharp - - using Microsoft.OpenApi.Any; - - using Microsoft.OpenApi.Models; - - - options.AddOperationTransformer((operation, context, ct) => - - { - var param = operation.Parameters.FirstOrDefault(p => p.Name == "api-version"); - if (param is not null) - { - param.Schema.Example = new OpenApiString("1.0"); - } - - operation.Responses.TryAdd("401", new OpenApiResponse { Description = "Unauthorized" }); - - var oAuthScheme = new OpenApiSecurityScheme - { - Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } - }; - operation.Security = new List - { - new() { [oAuthScheme] = scopes } - }; - - return Task.CompletedTask; - }); - - - options.AddSchemaTransformer((schema, context, ct) => - - { - if (schema.Properties is not null) - { - foreach (var property in schema.Properties) - { - if (schema.Required?.Contains(property.Key) != true) - property.Value.Nullable = false; - } - } - return Task.CompletedTask; - }); - - ``` - - - What changed and how do I fix each piece? - graders: - - type: output-matches - config: - pattern: (OpenApiString|OpenApiAny|JsonNode|System\.Text\.Json) - - type: output-matches - config: - pattern: (OpenApiSecurityScheme|Reference|OpenApiSecuritySchemeReference) - - type: output-matches - config: - pattern: (Nullable|nullable|removed|schema) - - type: prompt - rubric: - - Identifies OpenApiString/OpenApiAny types are removed; recommends using System.Text.Json.Nodes.JsonNode (e.g., - JsonNode.Parse) - - Identifies OpenApiSecurityScheme.Reference pattern is replaced by OpenApiSecuritySchemeReference - - Warns that operation.Parameters and other collections may now be null; must add null checks or initialize - - Identifies OpenApiSchema.Nullable is removed in OpenAPI 3.1 / Microsoft.OpenApi v2; schema transformer can be - removed or rewritten - - "Notes the namespace changes: Microsoft.OpenApi.Any removed, models moved to Microsoft.OpenApi" - - name: EF Core app with Azure SQL JSON columns and parameterized collections - prompt: | - I'm migrating a .NET 9 app using EF Core with UseAzureSql. The codebase: - - Has primitive collections (string[] Tags) and owned types mapped to JSON columns (currently nvarchar(max)) - - Uses .Contains() on List in LINQ queries that currently use OPENJSON - - The project multi-targets net9.0 and net10.0, and we run `dotnet ef migrations add` without --framework - What EF Core 10 breaking changes affect us? - graders: - - type: output-matches - config: - pattern: (json|nvarchar|data type) - - type: output-matches - config: - pattern: (parameterized|multiple parameters|OPENJSON|Contains) - - type: output-matches - config: - pattern: (--framework|multi-target) - - type: prompt - rubric: - - Warns about json data type replacing nvarchar(max) on Azure SQL and how to mitigate with - UseCompatibilityLevel(160) - - Explains parameterized collections changed from OPENJSON to multiple scalar parameters; provides - UseParameterizedCollectionMode mitigation - - Notes EF tools require --framework for multi-targeted projects - - name: EF Core app with dynamic ExecuteUpdate and complex types - prompt: | - I'm migrating a .NET 9 app using EF Core. Here's the code that builds dynamic ExecuteUpdateAsync calls: - ```csharp - Expression, SetPropertyCalls>> setters = - s => s.SetProperty(b => b.Views, 8); - if (nameChanged) - { - var blogParameter = Expression.Parameter(typeof(Blog), "b"); - setters = Expression.Lambda, SetPropertyCalls>>( - Expression.Call( - instance: setters.Body, - methodName: nameof(SetPropertyCalls.SetProperty), - typeArguments: new[] { typeof(string) }, - arguments: new Expression[] - { - Expression.Lambda>( - Expression.Property(blogParameter, nameof(Blog.Name)), blogParameter), - Expression.Constant("foo") - }), - setters.Parameters); - } - await context.Blogs.ExecuteUpdateAsync(setters); - ``` - - We also have complex types: - ```csharp - modelBuilder.Entity(b => { - b.ComplexProperty(c => c.ShippingAddress); - b.ComplexProperty(c => c.BillingAddress); - }); - // Both ShippingAddress and BillingAddress have a Street property - // Nested: Order.Payment.BillingAddress.City - ``` - - And a custom diagnostics logger: - ```csharp - public class MyLogger : IRelationalCommandDiagnosticsLogger - { - public InterceptionResult CommandReaderExecuting( - IRelationalConnection connection, DbCommand command, - DbContext context, Guid commandId, Guid connectionId, - DateTimeOffset startTime) - { /* logging */ } - } - ``` - What breaks in EF Core 10 and how do I fix each piece of code? - graders: - - type: output-matches - config: - pattern: (ExecuteUpdate|expression|lambda|Func) - - type: output-matches - config: - pattern: (complex type|column name|uniquif|full path) - - type: output-matches - config: - pattern: (logCommandText|diagnostics|logger|parameter) - - type: prompt - rubric: - - Identifies that ExecuteUpdateAsync now takes a regular lambda/delegate instead of an expression tree; shows the - simplified replacement using a regular lambda with if/else - - Warns about complex type column name uniquification — Street columns will get a number suffix - - Warns about nested complex type full-path column naming — BillingAddress_City becomes Payment_BillingAddress_City - - Identifies the missing logCommandText string parameter in CommandReaderExecuting - - name: SQLite app with DateTimeOffset timezone handling - prompt: > - I have a .NET 9 app using Microsoft.Data.Sqlite. It stores timestamps in TEXT columns without timezone offsets - (e.g., '2024-06-15 14:30:00') and reads them back with GetDateTimeOffset(). It also writes DateTimeOffset values - to REAL columns and reads timestamps with offsets using GetDateTime(). The app runs on machines in different - timezones and we rely on the current local-timezone interpretation. What changes in .NET 10? - graders: - - type: output-matches - config: - pattern: (UTC|timezone|time zone|offset) - - type: output-matches - config: - pattern: (GetDateTimeOffset|GetDateTime|DateTimeOffset) - - type: prompt - rubric: - - Explains GetDateTimeOffset without an offset now assumes UTC instead of local timezone - - Explains writing DateTimeOffset to REAL columns now converts to UTC first - - Explains GetDateTime with an offset now returns UTC with DateTimeKind.Utc instead of Local - - Mentions the AppContext switch Microsoft.Data.Sqlite.Pre10TimeZoneHandling as a temporary mitigation - - Warns that all three changes are high-impact and recommends reviewing all date/time handling code - - name: Worker service with config null array binding and ProviderAlias assembly change - prompt: > - I'm upgrading a .NET 9 worker service to .NET 10. I have specific concerns: - - - My appsettings.json has `"AllowedOrigins": [null, null]` and `"EmptyList": []`. In .NET 9, AllowedOrigins binds - as `["", ""]` and EmptyList binds as null. What happens in .NET 10? - - - I have `"ConnectionString": null` in my JSON config and my class has `public string ConnectionString { get; set; - } = "default";` — in .NET 9 this was bound as an empty string. Does this change? - - - My logging provider uses `[ProviderAlias("custom")]` and I reference it by assembly-qualified name - `Microsoft.Extensions.Logging.ProviderAliasAttribute, Microsoft.Extensions.Logging`. Will that still resolve? - - - I register services with `services.AddKeyedSingleton("redis")` and discover them with - `provider.GetKeyedServices(KeyedService.AnyKey)`. There was a bug in .NET 9 where this didn't work - correctly. Is it fixed? - - - My BackgroundService does database seeding synchronously at the start of ExecuteAsync before the first await, - and other services depend on the database being seeded. Will this still work? - graders: - - type: output-matches - config: - pattern: (null|empty|array|\[\]|binding) - - type: output-matches - config: - pattern: (ProviderAlias|Abstractions|assembly) - - type: output-matches - config: - pattern: (BackgroundService|ExecuteAsync|background thread|StartAsync) - - type: prompt - rubric: - - Correctly states AllowedOrigins will bind as [null, null] instead of ['', ''] in .NET 10 - - Correctly states EmptyList will bind as an empty array [] instead of null - - Correctly states ConnectionString will be overwritten with null, losing the 'default' constructor value - - Notes ProviderAliasAttribute moved from Microsoft.Extensions.Logging to - Microsoft.Extensions.Logging.Abstractions — assembly-qualified name will fail - - Confirms GetKeyedServices with AnyKey is fixed in .NET 10 - - Warns BackgroundService.ExecuteAsync now runs on a background thread; database seeding will not block startup; - recommends StartAsync or IHostedLifecycleService - - name: Cryptography app with OpenSSL, X.509, and Rfc2898DeriveBytes - prompt: | - I'm migrating a .NET 9 Linux server app to .NET 10. It: - - Uses OpenSSL-based crypto and runs on a system with OpenSSL 1.0.2 - - Also has a macOS build that uses SafeEvpPKeyHandle.OpenSslVersion to check the OpenSSL version - - Validates X.509 certificates and parses X500DistinguishedName values that sometimes have unusual formatting - - Uses new Rfc2898DeriveBytes(password, salt, iterations) to derive keys - - Uses ML-DSA (post-quantum) and accesses the SecretKey property - - Sets the DOTNET_SYSTEM_GLOBALIZATION_INVARIANT and old OpenSSL version override environment variables - What do I need to change? - graders: - - type: output-matches - config: - pattern: (OpenSSL|1\.1\.1|openssl) - - type: output-matches - config: - pattern: (macOS|unsupported) - - type: output-matches - config: - pattern: (Rfc2898|SYSLIB0060|Pbkdf2) - - type: output-matches - config: - pattern: (SecretKey|PrivateKey|renamed) - - type: prompt - rubric: - - Warns that OpenSSL 1.1.1+ is required on Unix — OpenSSL 1.0.2 is no longer supported - - Notes OpenSSL primitives are not supported on macOS - - Identifies Rfc2898DeriveBytes constructors as obsolete (SYSLIB0060) and recommends Rfc2898DeriveBytes.Pbkdf2 - - Identifies MLDsa SecretKey renamed to PrivateKey - - Mentions X500DistinguishedName validation is stricter - - Mentions DOTNET_OPENSSL_VERSION_OVERRIDE environment variable rename - - name: SDK and NuGet obscure tooling changes - prompt: > - I'm upgrading a .NET 9 project to .NET 10 and seeing unexpected behavior: - - - After `dotnet restore`, I get NU1510 warnings saying some of my direct PackageReferences have been "pruned". - What does this mean and how do I fix it? - - - I have a PackageReference to a package that only provides analyzers (no runtime assets). In .NET 9 it appeared - in deps.json but now it doesn't. Our deployment script reads deps.json to verify all expected packages are - present. - - - My project uses PrunePackageReference — how does this interact with direct references in .NET 10? - - - My CI script runs `dotnet new sln --name MySolution` and then parses the resulting .sln file to extract project - GUIDs. This broke. - - - My project has satellite resource assemblies for a custom culture (e.g., "x-custom"). The build behavior seems - different. - - - I have a PackageReference without a Version attribute because we were relying on implicit resolution from a - parent. Now restore fails. - - - Our CI sets NUGET_ENABLE_ENHANCED_HTTP_RETRY=true and uses HTTP (not HTTPS) NuGet sources with `dotnet package - list`. - - What changed? - graders: - - type: output-matches - config: - pattern: (NU1510|pruned|prune) - - type: output-matches - config: - pattern: (deps\.json|runtime assets) - - type: output-matches - config: - pattern: (SLNX|slnx|\.slnx|sln.*format) - - type: output-matches - config: - pattern: (PackageReference|[Vv]ersion|error) - - type: prompt - rubric: - - Explains NU1510 means the package is provided by the shared framework and the direct reference was pruned; - recommends removing the explicit PackageReference - - Notes packages with no runtime assets are no longer in deps.json; deployment script must be updated - - Explains PrunePackageReference now privatizes direct prunable references (PrivateAssets=All) - - Warns dotnet new sln creates SLNX format; recommends --format sln for CI scripts - - Notes MSBuild custom culture resource handling has changed - - Notes PackageReference without a version now raises an error instead of implicitly resolving - - Notes NUGET_ENABLE_ENHANCED_HTTP_RETRY env var was removed and HTTP sources now cause errors in dotnet package - list - - name: JSON polymorphism with conflicting property names and XmlSerializer - prompt: > - I'm migrating a .NET 9 app to .NET 10. Here's code that worked before: - - - ```csharp - - [JsonPolymorphic(TypeDiscriminatorPropertyName = "Type")] - - [JsonDerivedType(typeof(Dog), "dog")] - - public abstract class Animal - - { - public abstract string Type { get; } - } - - - public class Dog : Animal - - { - public override string Type => "Dog"; - } - - - // This produced {"Type":"dog","Type":"Dog"} in .NET 9 — broken JSON but it serialized - - string json = JsonSerializer.Serialize(new Dog()); - - ``` - - - ```csharp - - public class OrderDto - - { - public int Id { get; set; } - [Obsolete("Use ShippingAddress instead")] - public string Address { get; set; } - public string ShippingAddress { get; set; } - } - - var xml = new XmlSerializer(typeof(OrderDto)); - - // In .NET 9, Address was not included in the serialized output - - ``` - - - The app also validates email addresses like `user..name@example.com` with MailAddress, and uses Uri for 10K+ - character URLs. - - What breaks? - graders: - - type: output-matches - config: - pattern: (property name|conflict|\$type|discriminator|JsonIgnore|InvalidOperation) - - type: output-matches - config: - pattern: (XmlSerializer|Obsolete|XmlIgnore) - - type: output-matches - config: - pattern: (MailAddress|consecutive dots) - - type: prompt - rubric: - - Identifies the Animal/Dog Type property now throws InvalidOperationException because it conflicts with the - discriminator; recommends [JsonIgnore] or renaming - - Notes the [Obsolete] Address property will now be included in XML serialization; add [XmlIgnore] to exclude it - - Notes MailAddress now rejects consecutive dots - - Mentions Uri length limits have been removed - - name: WinForms and WPF desktop app with System.Drawing and DynamicResource - prompt: | - I'm upgrading a .NET 9 Windows desktop app to .NET 10. Here's code that needs migration: - - ```csharp - // Form1.cs - var menu = new ContextMenu(); - menu.MenuItems.Add(new MenuItem("Open", OnOpen)); - ``` - - ```csharp - // ImageProcessor.cs - try - { - using var bmp = new Bitmap(path); - bmp.SetResolution(300, 300); - } - catch (OutOfMemoryException ex) - { - logger.LogError(ex, "Invalid image format"); - } - ``` - - ```xml - - - - - - - ``` - - The project has both `true` and `true`. - The StatusStrip uses default rendering. TreeView has checkboxes. - What do I need to fix in each code snippet? - graders: - - type: output-matches - config: - pattern: (MenuItem|ContextMenu|disambiguate|ambiguous|fully qualified) - - type: output-matches - config: - pattern: (OutOfMemoryException|ExternalException) - - type: output-matches - config: - pattern: (ColumnDefinitions|RowDefinitions|empty|disallowed|remove) - - type: output-matches - config: - pattern: (DynamicResource|crash) - - type: prompt - rubric: - - Identifies MenuItem/ContextMenu ambiguity and shows fix with fully qualified System.Windows.Forms.MenuItem - - Identifies the catch block must change to catch ExternalException (not ArgumentException, not IOException — - specifically ExternalException from System.Runtime.InteropServices) - - Identifies the empty ColumnDefinitions/RowDefinitions must be removed from XAML - - Warns the DynamicResource with MissingKey will now crash instead of being silently ignored - - Mentions StatusStrip default RenderMode change - - Mentions TreeView checkbox image truncation change - - name: Containerized single-file app with P/Invoke and IDispatchEx - prompt: > - I'm migrating a .NET 9 app to .NET 10. Here's what we have: - - - ```dockerfile - - FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base - - RUN apt-get update && apt-get install -y libgdiplus libc6-dev - - FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build - - ``` - - - ```csharp - - // NativeInterop.cs - - [DllImport("mylib")] - - [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] - - static extern int ProcessData(byte* input, int length); - - ``` - - - ```csharp - - // ComHelper.cs - - var dispatchEx = (IDispatchEx)comObject; - - var reflect = (IReflect)dispatchEx; // cast to IReflect - - ``` - - - ```json - - // global.json - - { "sdk": { "version": "9.0.200" } } - - ``` - - - The app is published with `dotnet publish -r linux-x64 --self-contained /p:PublishSingleFile=true` and also has a - NativeAOT Linux build that relies on rpath. - - What needs to change for .NET 10? - graders: - - type: output-matches - config: - pattern: (Ubuntu|Debian|container|aspnet:10) - - type: output-matches - config: - pattern: (DllImport|AssemblyDirectory|single-file|System32) - - type: output-matches - config: - pattern: (IDispatchEx|IReflect|cast|COM) - - type: prompt - rubric: - - Updates the Dockerfile base images to 10.0 and warns that default images are now Ubuntu, not Debian; apt-get - commands may need adjustment - - Identifies the P/Invoke will fail to find mylib in the app directory because DllImportSearchPath.System32 - excludes it; recommends adding DllImportSearchPath.AssemblyDirectory - - Warns the IDispatchEx to IReflect cast now fails in .NET 10 - - Mentions NativeAOT rpath is no longer set automatically - - Notes global.json should be updated to 10.0.x SDK - - name: App using SslStream properties and SystemEvents - prompt: > - I'm upgrading a .NET 9 app to .NET 10. It: - - - Reads SslStream.KeyExchangeAlgorithm, SslStream.CipherAlgorithm, SslStream.HashAlgorithm, and their strength - properties for TLS connection logging - - - Registers a callback on SystemEvents.EventsThreadShutdown for cleanup - - - Uses Queryable.MaxBy with an IComparer overload - - - Has XSLT transforms with XsltSettings.EnableScript = true - - What warnings or errors will I get? - graders: - - type: output-matches - config: - pattern: (SYSLIB005[89]|NegotiatedCipherSuite|SslStream) - - type: output-matches - config: - pattern: (SYSLIB006[012]|EventsThreadShutdown|MaxBy|EnableScript) - - type: prompt - rubric: - - Identifies SYSLIB0058 for SslStream properties; recommends NegotiatedCipherSuite - - Identifies SYSLIB0059 for SystemEvents.EventsThreadShutdown; recommends AppDomain.ProcessExit - - Identifies SYSLIB0061 for Queryable.MaxBy/MinBy IComparer overloads - - Identifies SYSLIB0062 for XsltSettings.EnableScript - - name: Library with NuGet auditing, transitive deps, and InlineArray - prompt: | - I'm upgrading a .NET 9 class library to .NET 10. It: - - Has an [InlineArray(16)] struct with an explicit [StructLayout(LayoutKind.Explicit, Size = 64)] - - Uses DriveInfo.DriveFormat on Linux and compares the result to specific strings - - Uses dotnet restore and we're seeing new NU1510 warnings about pruned references - - The project has transitive NuGet dependencies that haven't been audited for vulnerabilities - - Has FilePatternMatch usage that checks if Stem is null - What should we fix? - graders: - - type: output-matches - config: - pattern: (InlineArray|StructLayout|explicit.*[Ss]ize|disallowed) - - type: output-matches - config: - pattern: (NU1510|pruned|transitive|audit) - - type: prompt - rubric: - - Warns that InlineArray structs with explicit Size in StructLayout are now disallowed (binary incompatible — - won't load) - - Explains DriveInfo.DriveFormat now returns actual Linux filesystem types instead of generic values - - Explains NU1510 for pruned references and recommends removing the explicit PackageReference - - Notes dotnet restore now audits transitive packages for vulnerabilities - - Mentions FilePatternMatch.Stem is now non-nullable - - name: C# 14 compiler breaking changes — field keyword, extension keyword, disposal - prompt: | - I'm migrating a .NET 9 library to .NET 10 / C# 14 and getting new compiler errors. Here's the code: - - ```csharp - // FieldParser.cs - public class FieldParser - { - private readonly JsonElement _payload; - - public string ParsedValue - { - get - { - _payload.TryGetProperty("field", out var field); - return field.GetString() ?? string.Empty; - } - } - } - ``` - - ```csharp - // Extension.cs - namespace MyLib.Plugins; - public class extension - { - public string Name { get; set; } - public void Load() { } - } - - // Used elsewhere: - using alias = MyLib.Plugins.extension; - ``` - - ```csharp - // Iteration.cs - var enumerator = GetItems().GetEnumerator(); - enumerator.MoveNext(); // True - var first = enumerator.Current; - enumerator.Dispose(); - enumerator.MoveNext(); // returned True in .NET 9, is this still the case? - var second = enumerator.Current; - ``` - - ```csharp - // LambdaHelper.cs - ref struct scoped { public int Value; } - var fn = (scoped scoped s) => s.Value; - ``` - - What breaks in each case and how do I fix it? - graders: - - type: output-matches - config: - pattern: (field|CS9272|CS9258|keyword|property accessor) - - type: output-matches - config: - pattern: (extension|keyword|contextual|rename|@extension) - - type: output-matches - config: - pattern: (enumerator|[Dd]ispos|MoveNext|false) - - type: prompt - rubric: - - Identifies 'var field' inside the property accessor as a CS9272 error because 'field' is now a keyword in - property accessors; recommends renaming to fieldValue/@field - - Identifies the class named 'extension' as breaking because extension is a contextual keyword in C# 14; - recommends renaming or using @extension - - Explains the enumerator now returns false from MoveNext() after disposal instead of continuing execution - - Identifies the scoped type name conflict in the lambda — scoped is treated as a modifier; recommends @scoped for - the type name - - name: Blazor WASM app with generic math shift masking and tar operations - prompt: | - I'm upgrading a .NET 9 Blazor WebAssembly app to .NET 10. Here's the code: - - ```csharp - // GenericShift.cs - static T ShiftLeft(T value, int amount) where T : IShiftOperators - => value << amount; - - // Usage: ShiftLeft(0xFF, 8) returned 0 for byte but we got - // inconsistent results with other small types in .NET 9 - ``` - - ```csharp - // ApiClient.cs - var response = await httpClient.GetAsync(url); - var stream = await response.Content.ReadAsStreamAsync(); - var buffer = new byte[4096]; - int bytesRead = stream.Read(buffer, 0, buffer.Length); // synchronous read - ``` - - ```csharp - // Archiver.cs - var entry = new PaxTarEntry(TarEntryType.RegularFile, "data.txt"); - // We expect entry.AccessTime and entry.ChangeTime to be set to now - archive.WriteEntry(entry); - ``` - - ```xml - - true - ``` - - What breaks in each case and how do I fix it? Note: the app also uses HTTP/3 to connect to our backend. - graders: - - type: output-matches - config: - pattern: (shift|mask|generic math|IShiftOperators|byte|sizeof) - - type: output-matches - config: - pattern: (streaming|synchronous|Read|browser|HttpClient|async) - - type: output-matches - config: - pattern: (HTTP/3|trim|PublishTrimmed|Http3Support) - - type: prompt - rubric: - - Explains that shift operations now consistently mask the shift amount; for byte, 8 & 7 = 0, so shifting by 8 - always returns 0 - - Identifies the synchronous stream.Read() now throws because browser streaming is enabled by default; must use - ReadAsync or disable streaming - - Notes PaxTarEntry no longer auto-populates atime/ctime; set them explicitly - - Notes HTTP/3 is disabled when PublishTrimmed is set; fix by adding true — this is - NOT a native library issue, it's the trimmer removing HTTP/3 code From 28ef5040c97fbcc993de02c234412fed277bd533 Mon Sep 17 00:00:00 2001 From: Julia Feng Date: Thu, 30 Jul 2026 11:44:35 -0700 Subject: [PATCH 2/5] adjust metadata --- .github/CODEOWNERS | 13 ------------- eng/allowed-external-deps.txt | 4 ---- eng/dashboard/generate-token-data.ps1 | 6 +++--- eng/eval-quality/underpowered-allowlist.txt | 7 ------- 4 files changed, 3 insertions(+), 27 deletions(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 1553e8b9b6..50046be494 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -31,11 +31,6 @@ /plugins/dotnet-upgrade/skills/migrate-nullable-references/ @agocke @dotnet/skills-upgrade-reviewers /tests/dotnet-upgrade/migrate-nullable-references/ @agocke @dotnet/skills-upgrade-reviewers -/plugins/dotnet-upgrade/skills/dotnet-aot-compat/ @agocke @dotnet/appmodel @dotnet/skills-upgrade-reviewers -/tests/dotnet-upgrade/dotnet-aot-compat/ @agocke @dotnet/appmodel @dotnet/skills-upgrade-reviewers - -/plugins/dotnet-upgrade/skills/migrate-dotnet9-to-dotnet10/ @dotnet/compat -/tests/dotnet-upgrade/migrate-dotnet9-to-dotnet10/ @dotnet/compat /plugins/dotnet-upgrade/skills/migrate-dotnet10-to-dotnet11/ @dotnet/compat /tests/dotnet-upgrade/migrate-dotnet10-to-dotnet11/ @dotnet/compat /plugins/dotnet-upgrade/skills/migrate-dotnet8-to-dotnet9/ @dotnet/compat @@ -51,18 +46,12 @@ /plugins/dotnet-diag/skills/dotnet-trace-collect/ @brianrob @noahfalk @dotnet/skills-diag-reviewers /tests/dotnet-diag/dotnet-trace-collect/ @brianrob @noahfalk @dotnet/skills-diag-reviewers -/plugins/dotnet-diag/skills/android-tombstone-symbolication/ @dotnet/dotnet-diag @dotnet/skills-diag-reviewers -/tests/dotnet-diag/android-tombstone-symbolication/ @dotnet/dotnet-diag @dotnet/skills-diag-reviewers - /plugins/dotnet-diag/skills/apple-crash-symbolication/ @dotnet/dotnet-diag @dotnet/skills-diag-reviewers /tests/dotnet-diag/apple-crash-symbolication/ @dotnet/dotnet-diag @dotnet/skills-diag-reviewers /plugins/dotnet-diag/skills/clr-activation-debugging/ @marklio @ChrisAhna @dotnet/skills-diag-reviewers /tests/dotnet-diag/clr-activation-debugging/ @marklio @ChrisAhna @dotnet/skills-diag-reviewers -/plugins/dotnet-diag/skills/microbenchmarking/ @dotnet/dotnet-perf-team @dotnet/skills-diag-reviewers -/tests/dotnet-diag/microbenchmarking/ @dotnet/dotnet-perf-team @dotnet/skills-diag-reviewers - /plugins/dotnet-diag/agents/optimizing-dotnet-performance.agent.md @dotnet/appmodel @dotnet/skills-diag-reviewers /plugins/dotnet/agents/optimizing-dotnet-performance.agent.md @dotnet/appmodel @@ -117,8 +106,6 @@ /tests/dotnet-maui/maui-app-lifecycle/ @davidortinau @Redth @jfversluis @dotnet/skills-maui-reviewers /plugins/dotnet-maui/skills/maui-dependency-injection/ @davidortinau @Redth @jfversluis @dotnet/skills-maui-reviewers /tests/dotnet-maui/maui-dependency-injection/ @davidortinau @Redth @jfversluis @dotnet/skills-maui-reviewers -/plugins/dotnet-maui/skills/maui-collectionview/ @davidortinau @Redth @jfversluis @dotnet/skills-maui-reviewers -/tests/dotnet-maui/maui-collectionview/ @davidortinau @Redth @jfversluis @dotnet/skills-maui-reviewers /plugins/dotnet-maui/skills/maui-data-binding/ @davidortinau @Redth @jfversluis @dotnet/skills-maui-reviewers /tests/dotnet-maui/maui-data-binding/ @davidortinau @Redth @jfversluis @dotnet/skills-maui-reviewers /plugins/dotnet-maui/skills/maui-safe-area/ @davidortinau @Redth @jfversluis @dotnet/skills-maui-reviewers diff --git a/eng/allowed-external-deps.txt b/eng/allowed-external-deps.txt index 4b286e3154..413c24ce51 100644 --- a/eng/allowed-external-deps.txt +++ b/eng/allowed-external-deps.txt @@ -13,10 +13,6 @@ # To get clean, remove entries as the underlying dependency is resolved. # Once this file is empty and all checks pass, the checks can be promoted to hard errors. -# dotnet-diag plugin: android-tombstone-symbolication skill -script:android-tombstone-symbolication:scripts/Symbolicate-Tombstone.ps1 -invokes:android-tombstone-symbolication - # dotnet-upgrade plugin: migrate-nullable-references skill script:migrate-nullable-references:scripts/Get-NullableReadiness.ps1 diff --git a/eng/dashboard/generate-token-data.ps1 b/eng/dashboard/generate-token-data.ps1 index ab8b3433d3..965d5e0fd2 100644 --- a/eng/dashboard/generate-token-data.ps1 +++ b/eng/dashboard/generate-token-data.ps1 @@ -18,11 +18,11 @@ $plugins = [ordered]@{ "dotnet" = @("csharp-scripts", "dotnet-pinvoke", "nuget-trusted-publishing") "dotnet-ai" = @("technology-selection") "dotnet-data" = @("optimizing-ef-core-queries") - "dotnet-diag" = @("analyzing-dotnet-performance", "android-tombstone-symbolication", "dotnet-trace-collect", "dump-collect", "microbenchmarking") + "dotnet-diag" = @("analyzing-dotnet-performance", "dotnet-trace-collect", "dump-collect") "dotnet-maui" = @("dotnet-maui-doctor") - "dotnet-msbuild" = @("binlog-failure-analysis", "build-parallelism", "build-perf-diagnostics", "incremental-build", "msbuild-antipatterns", "msbuild-modernization") + "dotnet-msbuild" = @("binlog-failure-analysis", "build-parallelism", "build-perf-diagnostics", "incremental-build", "msbuild-modernization") "dotnet-test" = @("migrate-vstest-to-mtp", "run-tests", "writing-mstest-tests") - "dotnet-upgrade" = @("dotnet-aot-compat", "migrate-dotnet9-to-dotnet10", "migrate-nullable-references") + "dotnet-upgrade" = @("migrate-nullable-references") } $random = [System.Random]::new(42) # Fixed seed for reproducibility diff --git a/eng/eval-quality/underpowered-allowlist.txt b/eng/eval-quality/underpowered-allowlist.txt index e0cd22701e..ae16e70d7c 100644 --- a/eng/eval-quality/underpowered-allowlist.txt +++ b/eng/eval-quality/underpowered-allowlist.txt @@ -28,27 +28,22 @@ tests/dotnet-advanced/csharp-scripts/eval.yaml tests/dotnet-aspnetcore/convert-blazor-server-to-webapp/eval.yaml tests/dotnet-data/optimizing-ef-core-queries/eval.yaml -tests/dotnet-diag/microbenchmarking/eval.yaml tests/dotnet-msbuild/binlog-failure-analysis/eval.yaml tests/dotnet-msbuild/build-parallelism/eval.yaml tests/dotnet-msbuild/build-perf-baseline/eval.yaml tests/dotnet-msbuild/build-perf-diagnostics/eval.yaml -tests/dotnet-msbuild/check-bin-obj-clash/eval.yaml tests/dotnet-msbuild/directory-build-organization/eval.yaml -tests/dotnet-msbuild/eval-performance/eval.yaml tests/dotnet-msbuild/including-generated-files/eval.yaml tests/dotnet-msbuild/incremental-build/eval.yaml tests/dotnet-msbuild/msbuild-modernization/eval.yaml tests/dotnet-msbuild/msbuild-server/eval.yaml tests/dotnet-msbuild/resolve-project-references/eval.yaml tests/dotnet-template-engine/template-instantiation/eval.yaml -tests/dotnet-upgrade/dotnet-aot-compat/eval.yaml tests/dotnet-advanced/dotnet-pinvoke/eval.yaml tests/dotnet-blazor/collect-user-input/eval.yaml tests/dotnet-blazor/configure-auth/eval.yaml tests/dotnet-blazor/coordinate-components/eval.yaml tests/dotnet-blazor/fetch-and-send-data/eval.yaml -tests/dotnet-blazor/support-prerendering/eval.yaml tests/dotnet-template-engine/template-authoring/eval.yaml tests/dotnet-template-engine/template-validation/eval.yaml tests/dotnet-advanced/nuget-trusted-publishing/eval.yaml @@ -71,13 +66,11 @@ tests/dotnet11/system-text-json-net11/eval.yaml tests/dotnet-blazor/use-js-interop/eval.yaml tests/dotnet-experimental/exp-test-maintainability/eval.yaml tests/dotnet-maui/maui-app-lifecycle/eval.yaml -tests/dotnet-maui/maui-collectionview/eval.yaml tests/dotnet-maui/maui-data-binding/eval.yaml tests/dotnet-maui/maui-dependency-injection/eval.yaml tests/dotnet-maui/maui-safe-area/eval.yaml tests/dotnet-maui/maui-shell-navigation/eval.yaml tests/dotnet-maui/maui-theming/eval.yaml -tests/dotnet-msbuild/msbuild-antipatterns/eval.yaml tests/dotnet-template-engine/template-smart-defaults/eval.yaml tests/dotnet-test/find-untested-sources/eval.yaml tests/dotnet-test/generate-testability-wrappers/eval.yaml From bdaaa3bf02daa00090059c72cb405a81f8d26bc2 Mon Sep 17 00:00:00 2001 From: Julia Feng Date: Thu, 30 Jul 2026 11:54:52 -0700 Subject: [PATCH 3/5] Keep dotnet-blazor skills on main --- eng/eval-quality/underpowered-allowlist.txt | 1 + .../skills/plan-ui-change/SKILL.md | 152 ++++++++ .../skills/support-prerendering/SKILL.md | 216 ++++++++++++ tests/dotnet-blazor/plan-ui-change/eval.yaml | 330 ++++++++++++++++++ .../support-prerendering/eval.yaml | 79 +++++ 5 files changed, 778 insertions(+) create mode 100644 plugins/dotnet-blazor/skills/plan-ui-change/SKILL.md create mode 100644 plugins/dotnet-blazor/skills/support-prerendering/SKILL.md create mode 100644 tests/dotnet-blazor/plan-ui-change/eval.yaml create mode 100644 tests/dotnet-blazor/support-prerendering/eval.yaml diff --git a/eng/eval-quality/underpowered-allowlist.txt b/eng/eval-quality/underpowered-allowlist.txt index ae16e70d7c..1da399d04a 100644 --- a/eng/eval-quality/underpowered-allowlist.txt +++ b/eng/eval-quality/underpowered-allowlist.txt @@ -44,6 +44,7 @@ tests/dotnet-blazor/collect-user-input/eval.yaml tests/dotnet-blazor/configure-auth/eval.yaml tests/dotnet-blazor/coordinate-components/eval.yaml tests/dotnet-blazor/fetch-and-send-data/eval.yaml +tests/dotnet-blazor/support-prerendering/eval.yaml tests/dotnet-template-engine/template-authoring/eval.yaml tests/dotnet-template-engine/template-validation/eval.yaml tests/dotnet-advanced/nuget-trusted-publishing/eval.yaml diff --git a/plugins/dotnet-blazor/skills/plan-ui-change/SKILL.md b/plugins/dotnet-blazor/skills/plan-ui-change/SKILL.md new file mode 100644 index 0000000000..541736ae90 --- /dev/null +++ b/plugins/dotnet-blazor/skills/plan-ui-change/SKILL.md @@ -0,0 +1,152 @@ +--- +license: MIT +name: plan-ui-change +description: > + Plan complex Blazor UI features by decomposing them into focused components. + USE FOR: building a complex Blazor page with multiple sections, planning + component decomposition, designing a multi-section dashboard or layout, + breaking down a large UI feature into composable components, pages with + sidebars and content panels, any page with 3+ distinct visual sections + or multiple interacting sub-features, identifying parent-child relationships + and data flow. + DO NOT USE FOR: creating new Blazor projects or apps from scratch + (use create-blazor-project), implementing a single individual component + (use author-component), writing component code with parameters and + EventCallback (use author-component), or simple single-component pages. +--- + +# Plan a Blazor UI Change + +When asked to build a complex UI feature, **plan the component decomposition first, then immediately implement it**. A single monolithic page component is almost never the right answer — break the UI into focused, composable components. + +## Planning Workflow + +### Step 1 — Map the Visual Regions + +Read the request and identify every distinct visual region. Each region that has its own data, behavior, or layout responsibility is a candidate component. + +Draw the component tree: + +``` +InventoryDashboard (page — owns data, orchestrates layout) +├── StockSummaryBar (read-only stats: total items, low-stock count, value) +├── InventoryFilters (search box, category dropdown, stock-level toggle) +├── InventoryTable (sortable table of products) +│ └── InventoryRow (single product row with inline edit/delete) +└── AddProductForm (slide-out form for new products) +``` + +Rules for identifying components: +- **Distinct responsibility** — a region owns its own state or behavior → separate component +- **Repeated structure** — items in a list, cards in a grid → extract the item template +- **Independent interactivity** — a section that handles user input separately from its siblings → separate component +- **Size** — any section that would exceed ~150 lines of markup on its own → split it + +### Step 2 — Classify Each Component + +For every component in the tree, determine: + +| Component | Action | Render Mode | State Owned | Lines (est.) | +|-----------|--------|-------------|-------------|-------------| +| InventoryDashboard | Create | InteractiveServer | product list, filter state | ~80 | +| StockSummaryBar | Create | (inherits) | none — receives data | ~30 | +| InventoryFilters | Create | (inherits) | search text, selected category | ~60 | +| InventoryTable | Create | (inherits) | sort column, sort direction | ~50 | +| InventoryRow | Create | (inherits) | inline-edit mode flag | ~60 | +| AddProductForm | Create | (inherits) | form model | ~80 | + +**A page component that exceeds ~200 lines of combined markup + code is too large.** If your estimate puts a single component above that, split further. + +### Step 3 — Design Data Flow + +Identify the **state owner** for each piece of data, then map how it flows: + +``` +InventoryDashboard (owns: products[], filters) + │ + ├─ [Parameter] products ──→ StockSummaryBar (reads aggregate stats) + │ + ├─ [Parameter] filters ──→ InventoryFilters + │ └─ EventCallback OnFiltersChanged ──→ InventoryDashboard + │ + ├─ [Parameter] filteredProducts ──→ InventoryTable + │ └─ [Parameter] product ──→ InventoryRow + │ ├─ EventCallback OnSave ──→ InventoryTable ──→ InventoryDashboard + │ └─ EventCallback OnDelete ──→ InventoryTable ──→ InventoryDashboard + │ + └─ EventCallback OnProductAdded ←── AddProductForm +``` + +Rules: +- Data always flows **down** through `[Parameter]` +- Events always flow **up** through `EventCallback` +- The page/parent **owns the data** and passes filtered/transformed views to children +- Children **never mutate parameters** — they notify the parent via callbacks +- If data must cross more than 2 levels without intermediate components needing it, use a cascading value or a scoped service + +### Step 4 — Identify Reuse Opportunities + +Before creating a new component, check if an existing component in the project can serve the purpose. Look for: +- Existing list-item components that match the structure +- Shared filter/search components already in the project +- Generic components (e.g., `DataTable`, `Pagination`) that accept templates + +If a component will be used in more than one page, place it in a `Shared/` or `Components/` folder. + +### Step 5 — Order the Implementation + +Build bottom-up — leaf components first, then parents that compose them: + +1. **Models/DTOs** — define the data shapes +2. **Services** — data access, business logic (interface + implementation) +3. **Leaf components** — components with no children (InventoryRow, StockSummaryBar) +4. **Container components** — components that compose leaves (InventoryTable, InventoryFilters) +5. **Page component** — wires everything together, registers routes +6. **Configuration** — DI registration, render mode setup + +Each component should be independently compilable. Never reference a component that doesn't exist yet. + +## Output Format + +Present the plan briefly, then **immediately proceed to implement** — never stop at just the plan or ask for confirmation before writing code. The plan is a thinking tool, not a deliverable. + +```markdown +## Component Plan: [Feature Name] + +### Component Tree +[ASCII tree showing parent-child relationships] + +### Component Table +| Component | Action | Render Mode | Purpose | Est. Lines | +|-----------|--------|-------------|---------|------------| +| ... | ... | ... | ... | ... | + +### Data Flow +[State owner] → [Parameters down] → [EventCallbacks up] + +### Implementation Order +1. [First file to create — why] +2. [Second file — why] +... +``` + +After outputting the plan, **immediately begin implementing** the components in the order listed. Do not wait for approval or ask "shall I proceed?" — the plan is a guide for you to follow, not a proposal for the user to approve. + +## Anti-Patterns to Avoid + +| Anti-Pattern | Why It's Wrong | Correct Approach | +|-------------|----------------|-----------------| +| One page component with 500+ lines | Impossible to test, reuse, or maintain | Decompose into focused components | +| Passing 10+ parameters through intermediate components | Parameter drilling obscures intent | Use cascading values or a scoped state service | +| Child component fetching its own data from an API | Multiple components making redundant calls | Parent owns data, passes via parameters | +| Inline rendering of list items with complex markup | Duplicated logic, no reuse, hard to test | Extract item template into its own component | +| Building everything in one file then "refactoring later" | Refactoring rarely happens; the monolith ships | Plan the decomposition upfront | +| Generic components for one-off usage | Over-engineering adds complexity | Only extract generics when reuse is proven | + +## Guidelines + +- **Plan briefly, then implement.** Write a concise component table and data flow map, then immediately create the `.razor` files — never stop at just the plan. +- **Prefer many small components over one large one.** A component with a single clear purpose is easier to understand, test, and reuse. +- **State ownership is the first decision.** Before writing fetch logic, decide which component owns the data. +- **Build bottom-up.** Create leaf components first so parent components can reference them immediately. +- **Name components after what they render**, not what they do internally: `ProductCard` not `ProductRenderer`, `OrderFilters` not `FilterHandler`. diff --git a/plugins/dotnet-blazor/skills/support-prerendering/SKILL.md b/plugins/dotnet-blazor/skills/support-prerendering/SKILL.md new file mode 100644 index 0000000000..33495a887d --- /dev/null +++ b/plugins/dotnet-blazor/skills/support-prerendering/SKILL.md @@ -0,0 +1,216 @@ +--- +license: MIT +name: support-prerendering +description: Make interactive Blazor components work correctly with prerendering. USE FOR fixing duplicate data loads, UI flicker during prerender-to-interactive handoff, null references during prerender, persisting state across prerender, disabling prerendering, excluding pages from interactive routing, or detecting whether a component is currently prerendering. DO NOT USE for choosing which render mode to use (see create-blazor-project) or general component authoring (see author-component). +--- + +# Support Prerendering + +## How Prerendering Works + +Prerendering is **on by default** for all interactive render modes. The server renders the component as static HTML and ships it to the browser immediately. Then the interactive runtime (Server/WebAssembly) loads and re-renders the component with full interactivity. + +This means: +- `OnInitializedAsync` runs **twice** — once during prerender (static), once when the interactive runtime attaches. +- `OnAfterRenderAsync` is **NOT** called during prerender — only after the interactive render. +- Internal navigation between interactive pages (interactive routing) **skips prerendering** — prerendering only happens on full page loads. + +## Step 1 — Read the Project's AGENTS.md + +Check the project's `AGENTS.md` for the **Interactivity Mode** and **Interactivity Scope**: + +| Mode | Prerendering applies? | +|------|----------------------| +| None (Static SSR) | No — there's no interactive handoff | +| Server | Yes | +| WebAssembly | Yes | +| Auto | Yes | + +If the mode is `None`, this skill doesn't apply. + +## Persist State Across Prerender → Interactive + +The most common prerendering problem: data loaded in `OnInitializedAsync` during prerender is thrown away and re-fetched when the interactive runtime attaches. This causes flicker and duplicate API/DB calls. + +### Recommended: `[PersistentState]` attribute + +Annotate properties to automatically serialize during prerender and restore on interactive activation: + +```razor +@page "/forecasts" +@rendermode InteractiveServer + +

Weather

+ +@if (Forecasts is null) +{ +

Loading...

+} +else +{ + @foreach (var f in Forecasts) + { +

@f.Date: @f.TemperatureC°C

+ } +} + +@code { + [PersistentState] + public WeatherForecast[]? Forecasts { get; set; } + + protected override async Task OnInitializedAsync() + { + Forecasts ??= await ForecastService.GetForecastsAsync(); + } +} +``` + +The `??=` pattern is critical — it means "only fetch if the property wasn't already restored from prerender state." + +### Multiple instances of the same component + +When the same component type appears multiple times, use `@key` to disambiguate state: + +```razor +@foreach (var item in items) +{ + +} +``` + +### Advanced: `PersistentComponentState` service + +For complex scenarios (dynamic keys, custom serialization), use the imperative API: + +```csharp +@inject PersistentComponentState ApplicationState + +@code { + private List? orders; + + protected override async Task OnInitializedAsync() + { + ApplicationState.RegisterOnPersisting(PersistOrders); + + if (!ApplicationState.TryTakeFromJson>("orders", out var restored)) + { + orders = await OrderService.GetOrdersAsync(); + } + else + { + orders = restored; + } + } + + private Task PersistOrders() + { + ApplicationState.PersistAsJson("orders", orders); + return Task.CompletedTask; + } +} +``` + +## Disable Prerendering + +Disable prerendering when a component depends on browser APIs immediately or when the prerender+interactive double render causes problems you can't solve with `[PersistentState]`. + +### On a component definition + +```razor +@rendermode @(new InteractiveServerRenderMode(prerender: false)) +``` + +Replace `InteractiveServerRenderMode` with `InteractiveWebAssemblyRenderMode` or `InteractiveAutoRenderMode` as needed. + +### On a component instance + +```razor + +``` + +### On the entire app + +In `App.razor`: + +```razor + + +``` + +Note: A parent's prerendering setting overrides children. If `` disables prerendering, individual pages cannot re-enable it. + +## Exclude Pages from Interactive Routing + +In a globally interactive app, some pages may need `HttpContext` (cookies, request headers, response status codes). These pages must render via static SSR, not inside the interactive runtime. + +Use `[ExcludeFromInteractiveRouting]`: + +```razor +@page "/privacy" +@attribute [ExcludeFromInteractiveRouting] + +

Privacy Policy

+``` + +This forces a **full page reload** when navigating to this page, exiting interactive routing. The page renders as static SSR with full `HttpContext` access. + +In `App.razor`, conditionally apply the render mode: + +```razor + + + + + + + + + + + +@code { + [CascadingParameter] + public HttpContext HttpContext { get; set; } = default!; + + private IComponentRenderMode? RenderModeForPage => + HttpContext.AcceptsInteractiveRouting() ? InteractiveServer : null; +} +``` + +Replace `InteractiveServer` with the app's configured render mode. + +## Detect Prerender vs Interactive at Runtime + +Use `RendererInfo` to guard code that should only run interactively: + +```csharp +protected override async Task OnInitializedAsync() +{ + if (RendererInfo.IsInteractive) + { + // Only runs during the interactive render, not during prerender + await StartSignalRConnection(); + } +} +``` + +`RendererInfo` properties: +- `IsInteractive` — `false` during prerender, `true` after interactive runtime attaches +- `Name` — `"Static"` during prerender, `"Server"` or `"WebAssembly"` when interactive + +## Client Services Fail During Prerender + +Components in the `.Client` project prerender on the server. Services registered only in the client `Program.cs` (e.g., `IWebAssemblyHostEnvironment`) won't be available during prerender. + +Fix by one of: +1. **Register a matching service on the server** — both `Program.cs` files provide the service +2. **Make the service optional** — use constructor injection with a nullable default: `public MyComponent(IMyService? svc = null)` +3. **Create a service abstraction** — interface in `.Client`, implementations in both projects +4. **Disable prerendering** for that component + +## Don'ts + +- Don't call JS interop in `OnInitializedAsync` — JS isn't available during prerender. Use `OnAfterRenderAsync(firstRender)`. +- Don't assume `OnInitializedAsync` runs once — it runs twice with prerendering. Always use `[PersistentState]` or `??=` guards. +- Don't use `HttpContext` in interactive components — it's only available during the static prerender, not during the interactive lifetime. Use `[ExcludeFromInteractiveRouting]` for pages that need it. +- Don't disable prerendering as a first resort — it hurts perceived load time and SEO. Use `[PersistentState]` to preserve state instead. diff --git a/tests/dotnet-blazor/plan-ui-change/eval.yaml b/tests/dotnet-blazor/plan-ui-change/eval.yaml new file mode 100644 index 0000000000..08af2ccb51 --- /dev/null +++ b/tests/dotnet-blazor/plan-ui-change/eval.yaml @@ -0,0 +1,330 @@ +name: plan-ui-change +description: Evaluates the dotnet-blazor/plan-ui-change skill +type: capability +config: + timeout: 40m +stimuli: + - name: Project management Kanban board + prompt: | + Build a Blazor page for a project management Kanban board. This is a complex + multi-section layout. Here are the service contracts + already registered in DI: + + ```csharp + public record TaskItem(int Id, string Title, string Assignee, string Priority, DateTime DueDate, string Status); + + public interface ITaskService + { + Task> GetAllTasksAsync(); + Task CreateTaskAsync(string title, string assignee, string priority, DateTime dueDate); + Task UpdateTaskStatusAsync(int taskId, string newStatus); + } + ``` + + The page should have: + - A summary stats bar at the top showing: total task count, count per column (To Do, In Progress, Done), + and a count of overdue tasks (DueDate < today) + - A search bar that filters visible tasks by title (client-side filtering) + - Three columns side by side: "To Do", "In Progress", "Done" + - Each column header shows the column name and the number of tasks in it + - Each column displays task cards showing: title, assignee name, a priority badge (High = red, + Medium = yellow, Low = green CSS class), and the due date formatted as "MMM dd" + - Each task card has "Move Left" and "Move Right" buttons to move the task to the adjacent column + (hide the button if there's no column in that direction). Moving a task calls UpdateTaskStatusAsync + - Each column has an "Add Task" button at the bottom. Clicking it reveals an inline form within that + column with inputs for title, assignee, priority (dropdown: High/Medium/Low), and due date. + A "Save" button calls CreateTaskAsync and a "Cancel" button hides the form + - The page loads all tasks on initialization and handles loading/error states + + Route: `/board` + environment: + commands: + - dotnet new blazor --interactivity Server --no-https + graders: + - type: output-contains + config: + substring: '[Parameter]' + - type: output-contains + config: + substring: EventCallback + - type: output-matches + config: + pattern: (ITaskService|TaskItem) + - type: prompt + rubric: + - The board is organized into focused, reusable components — task cards, columns, and the stats bar are separate from the page itself + - State changes in child components propagate correctly to the parent and other siblings — e.g., moving a task updates the column counts + - Handles loading and error states with conditional rendering (@if/@else) + - name: E-commerce product catalog with filters and pagination + prompt: | + Build a Blazor page for browsing a product catalog. Here are the service contracts + already registered in DI: + + ```csharp + public record Product(int Id, string Name, decimal Price, string Category, double Rating, bool InStock, string ImageUrl); + public record ProductFilter(List? Categories, decimal? MinPrice, decimal? MaxPrice, bool InStockOnly); + public record PagedResult(List Items, int TotalCount, int Page, int PageSize); + + public interface IProductService + { + Task> SearchAsync(ProductFilter filter, string sortBy, int page, int pageSize); + Task> GetCategoriesAsync(); + } + ``` + + The page layout should have: + - A left sidebar (about 25% width) with filter controls: + - Category checkboxes (loaded from GetCategoriesAsync) + - Min price and max price number inputs + - An "In Stock Only" checkbox toggle + - An "Apply Filters" button that triggers a new search + - A "Clear Filters" button that resets all filters to defaults + - A main content area (about 75% width) with: + - A toolbar row containing: a sort dropdown (options: "Price: Low to High", "Price: High to Low", + "Name: A-Z", "Rating: Highest"), and a "Showing X–Y of Z products" label + - A product grid displaying product cards, each showing: a placeholder image div with the product name + as alt text, the product name, the price formatted as currency, a star rating display (e.g., "★★★★☆" + for 4/5), an "Out of Stock" badge if not in stock, and an "Add to Cart" button (disabled when out of stock) + - When a product card is clicked (not the Add to Cart button), the parent should be notified via + EventCallback so it can navigate to a detail page + - Pagination controls at the bottom: "Previous" button (disabled on first page), numbered page buttons, + "Next" button (disabled on last page) + - The page loads the first page of products and the category list on initialization + - Handle loading, empty results, and error states + + Route: `/catalog` + environment: + commands: + - dotnet new blazor --interactivity Server --no-https + graders: + - type: output-contains + config: + substring: '[Parameter]' + - type: output-contains + config: + substring: EventCallback + - type: output-matches + config: + pattern: (IProductService|ProductFilter|PagedResult) + - type: prompt + rubric: + - The catalog uses a multi-component architecture — product cards, filter sidebar, and pagination are separate reusable units + - Child components communicate changes back to the parent via defined interfaces — e.g., filter sidebar notifies the page when filters change, pagination notifies on page change + - Filtering, sorting, and pagination all work together — changing filters resets to page 1, changing sort re-fetches + - Handles loading, empty, and error states with conditional rendering + - name: Multi-step job application wizard + prompt: | + Build a Blazor page for a multi-step job application form. This has many + distinct visual sections and shared state. Here are the service contracts already registered in DI: + + ```csharp + public record JobApplication(PersonalInfo Personal, WorkHistory Work, List References, string CoverLetter); + public record PersonalInfo(string FullName, string Email, string Phone, string Address); + public record WorkHistory(List Entries); + public record WorkEntry(string Company, string Title, DateTime StartDate, DateTime? EndDate, string Description); + public record Reference(string Name, string Relationship, string Email, string Phone); + + public interface IApplicationService + { + Task SubmitApplicationAsync(JobApplication application); + Task ValidateEmailAsync(string email); + } + ``` + + The page should have: + + **Step indicator bar:** + - Shows all steps: "Personal Info" → "Work History" → "References" → "Cover Letter" → "Review & Submit" + - The current step is highlighted, completed steps show a checkmark, future steps are dimmed + - Users can click a completed step to go back and edit it + + **Step 1 — Personal Info:** + - Inputs for full name, email, phone, and address + - Email is validated via ValidateEmailAsync when the user moves to the next step + - A "Next" button that validates required fields before advancing + + **Step 2 — Work History:** + - A dynamic list of work entries — start with one empty entry + - Each entry has: company name, job title, start date, end date (optional, checkbox for "current"), description + - "Add Another Position" button to add more entries + - "Remove" button on each entry (except if it's the only one) + - "Back" and "Next" buttons + + **Step 3 — References:** + - Space for 2-3 references, each with: name, relationship, email, phone + - "Add Reference" button (max 3) + - "Back" and "Next" buttons + + **Step 4 — Cover Letter:** + - A large textarea for the cover letter + - A character count display (e.g., "342 / 2000 characters") + - "Back" and "Next" buttons + + **Step 5 — Review & Submit:** + - Read-only summary of all entered data organized by section + - An "Edit" link next to each section that jumps back to that step + - A "Submit Application" button that calls SubmitApplicationAsync + - After submission, show a confirmation with the application ID + + Route: `/apply` + environment: + commands: + - dotnet new blazor --interactivity Server --no-https + graders: + - type: output-contains + config: + substring: '[Parameter]' + - type: output-contains + config: + substring: EventCallback + - type: output-matches + config: + pattern: (IApplicationService|JobApplication) + - type: prompt + rubric: + - The wizard is decomposed so each step lives in its own component — navigation flows between them rather than toggling visibility in one file + - Step data is passed down via parameters and changes flow up via callbacks — steps don't share or mutate parent state directly + - Navigation between steps validates before advancing — prevents skipping required fields + - The review step displays a read-only summary of all steps and supports going back to edit a specific step + - name: Application settings page with nested tab panels + prompt: | + Build a Blazor page for an application settings dashboard. This has multiple + nested sections. Here are the service contracts + already registered in DI: + + ```csharp + public record UserProfile(string DisplayName, string Email, string AvatarUrl, string Bio); + public record NotificationPrefs(bool EmailNotifications, bool PushNotifications, bool WeeklyDigest, List MutedChannels); + public record SecuritySettings(bool TwoFactorEnabled, DateTime? LastPasswordChange, List Sessions); + public record ActiveSession(string Id, string Device, string Location, DateTime LastActive); + public record AppearanceSettings(string Theme, string FontSize, string Language, bool CompactMode); + + public interface ISettingsService + { + Task GetProfileAsync(); + Task SaveProfileAsync(UserProfile profile); + Task GetNotificationPrefsAsync(); + Task SaveNotificationPrefsAsync(NotificationPrefs prefs); + Task GetSecuritySettingsAsync(); + Task ChangePasswordAsync(string currentPassword, string newPassword); + Task RevokeSessionAsync(string sessionId); + Task GetAppearanceAsync(); + Task SaveAppearanceAsync(AppearanceSettings settings); + } + ``` + + The page should have: + + **Left sidebar navigation (vertical tabs):** + - Four sections: "Profile", "Notifications", "Security", "Appearance" + - The active section is highlighted + - Clicking a section loads its content in the main area + + **Profile section:** + - Editable fields: display name, email, bio (textarea) + - An avatar preview area with the current URL displayed + - A "Save Changes" button — shows a success toast/message on save + - A "Discard Changes" button that reverts to the last saved state + + **Notifications section:** + - Toggle switches for: email notifications, push notifications, weekly digest + - A list of channels with checkboxes to mute/unmute each + - A "Save Preferences" button + + **Security section:** + - A "Change Password" expandable panel with: current password, new password, confirm password fields and a "Update Password" button + - Two-factor authentication toggle with status indicator + - An "Active Sessions" table showing: device, location, last active time, and a "Revoke" button for each session (except the current one) + - A confirmation dialog before revoking a session + + **Appearance section:** + - Theme selector: radio buttons for "Light", "Dark", "System" + - Font size selector: "Small", "Medium", "Large" + - Language dropdown + - Compact mode toggle + - A live preview area that shows how the selected options look + - A "Save" button + + Route: `/settings` + environment: + commands: + - dotnet new blazor --interactivity Server --no-https + graders: + - type: output-contains + config: + substring: '[Parameter]' + - type: output-contains + config: + substring: EventCallback + - type: output-matches + config: + pattern: (ISettingsService|UserProfile|SecuritySettings) + - type: prompt + rubric: + - Each settings section (Profile, Notifications, Security, Appearance) is its own component — not all inlined in the page + - Switching tabs loads the correct section content without a full page reload + - Handles the save/discard flow with appropriate UI feedback (success message, disabled buttons during save) + - name: Team chat interface with message threads + prompt: | + Build a Blazor page for a team messaging app. This is a complex multi-panel + layout with a sidebar, main area, and collapsible thread panel. Here are the service contracts + already registered in DI: + + ```csharp + public record Channel(int Id, string Name, string Description, int UnreadCount); + public record Message(int Id, int ChannelId, string Author, string Content, DateTime SentAt, int? ReplyToId, List Reactions); + public record Reaction(string Emoji, List Users); + public record ThreadSummary(int RootMessageId, int ReplyCount, DateTime LastReplyAt); + + public interface IChatService + { + Task> GetChannelsAsync(); + Task> GetMessagesAsync(int channelId, int skip, int take); + Task SendMessageAsync(int channelId, string content, int? replyToId); + Task> GetThreadAsync(int rootMessageId); + Task AddReactionAsync(int messageId, string emoji); + Task MarkChannelReadAsync(int channelId); + } + ``` + + The page layout should have: + + **Left sidebar (channel list, about 20% width):** + - A list of channels, each showing: channel name (with # prefix), description snippet, and an unread count badge + - The active channel is highlighted + - Clicking a channel loads its messages in the main area and marks it as read + + **Main message area (about 55% width, or 80% if no thread is open):** + - A header showing the current channel name and description + - A scrollable message list showing messages for the selected channel + - Each message displays: author name, timestamp (relative — "2 min ago"), message content, and a row of reaction emoji badges (each showing emoji + count) + - Hovering a message reveals action buttons: "Reply" (opens thread panel), "React" (shows emoji picker with 5-6 common emojis) + - Messages that are thread starters show a "N replies" link below them + - A message input area at the bottom: a textarea and a "Send" button + - Load older messages on scroll-to-top (pagination via skip/take) + + **Right panel (thread view, about 25% width, shown when a thread is open):** + - Header: "Thread" with the original message quoted and a close button + - A scrollable list of reply messages in the thread + - A reply input area at the bottom (textarea + "Reply" button) + - Closing the thread panel widens the main message area back + + Route: `/chat` + environment: + commands: + - dotnet new blazor --interactivity Server --no-https + graders: + - type: output-contains + config: + substring: '[Parameter]' + - type: output-contains + config: + substring: EventCallback + - type: output-matches + config: + pattern: (IChatService|Message|Channel) + - type: prompt + rubric: + - The chat interface is decomposed into focused components — channel list, message area, thread panel, and message input each have clear responsibilities + - The message input component is reused in both the main area and thread panel + - Channel selection, sending messages, and opening threads all work correctly — selecting a channel loads its messages, opening a thread shows replies diff --git a/tests/dotnet-blazor/support-prerendering/eval.yaml b/tests/dotnet-blazor/support-prerendering/eval.yaml new file mode 100644 index 0000000000..dcb9022ac2 --- /dev/null +++ b/tests/dotnet-blazor/support-prerendering/eval.yaml @@ -0,0 +1,79 @@ +name: support-prerendering +description: Evaluates the dotnet-blazor/support-prerendering skill +type: capability +config: + timeout: 10m +stimuli: + - name: Equipment inventory loaded once + prompt: | + I have an existing Blazor Web App with Interactive Server (per-page). + + I need an interactive /inventory page that shows a table of equipment items + (Id, Name, Location, LastInspected date). The data comes from an EquipmentService + you should create (just return fake data, 5-10 items). + + The page should show "Loading inventory..." until data is ready, then display + the table. The important thing is that when the page first loads I see the HTML + instantly (fast initial paint), but the equipment data should NOT be fetched + twice — once during the initial server render and again when the page becomes + interactive. It should only call the service once and carry that data across. + graders: + - type: file-exists + config: + path: '**/Inventory.razor' + - type: file-contains + config: + path: '**/Inventory.razor' + value: PersistentState + - type: file-contains + config: + path: '**/Inventory.razor' + value: InteractiveServer + - type: file-contains + config: + path: '**/Inventory.razor' + value: '??=' + - type: prompt + rubric: + - Data persists across the prerender-to-interactive handoff — uses state persistence ([PersistentState] or PersistentComponentState) with ??= pattern to avoid duplicate data fetches + - Component correctly shows loading state when data is null, then displays the equipment table when loaded + - Does NOT disable prerendering — preserves the fast initial HTML response while avoiding duplicate loads + - Creates a proper EquipmentService registered in DI, not inline data generation + - name: Notifications page with live polling + prompt: | + I have an existing Blazor Web App with Interactive Server (per-page). + + I need an interactive /notifications page that: + - Loads an initial set of notifications from a NotificationService (create it with fake data) + - After the page becomes interactive, starts a background polling loop that + checks for new notifications every 5 seconds and updates the UI + - Shows a notification count badge and a list of notification messages + + Important constraints: + - The initial notifications should appear in the fast server-rendered HTML + and NOT be fetched again when the page becomes interactive + - The polling loop must not run during the initial server render — only after + the page is live and interactive in the browser + - When the user navigates away, the polling should stop cleanly (no leaked tasks) + graders: + - type: file-exists + config: + path: '**/Notifications.razor' + - type: file-contains + config: + path: '**/Notifications.razor' + value: RendererInfo.IsInteractive + - type: file-contains + config: + path: '**/Notifications.razor' + value: PersistentState + - type: file-contains + config: + path: '**/Notifications.razor' + value: InteractiveServer + - type: prompt + rubric: + - Guards the polling loop so it only runs when the component is interactive — not during prerendering + - Persists initial notification data across the prerender-to-interactive handoff so the service is not called twice + - Polling uses an async loop with CancellationTokenSource, cancelled in DisposeAsync — not System.Threading.Timer + - Component implements IAsyncDisposable and cancels the polling token in DisposeAsync to prevent resource leaks From 70e0f1e7365a7fa6a97a8eff655df65355ee9904 Mon Sep 17 00:00:00 2001 From: Julia Feng Date: Thu, 30 Jul 2026 12:34:02 -0700 Subject: [PATCH 4/5] Keep microbenchmarking on main --- .github/CODEOWNERS | 3 + eng/dashboard/generate-token-data.ps1 | 2 +- eng/eval-quality/underpowered-allowlist.txt | 1 + .../skills/microbenchmarking/SKILL.md | 137 ++++++++ .../references/bdn-internals-and-tuning.md | 132 ++++++++ .../references/comparison-strategies.md | 188 +++++++++++ .../references/diagnosers-and-exporters.md | 143 +++++++++ .../references/project-setup-and-running.md | 179 +++++++++++ .../references/writing-benchmarks.md | 296 ++++++++++++++++++ .../TextAnalyzer/TextAnalyzer.cs | 64 ++++ .../TextAnalyzer/TextAnalyzer.csproj | 7 + tests/dotnet-diag/microbenchmarking/eval.yaml | 38 +++ 12 files changed, 1189 insertions(+), 1 deletion(-) create mode 100644 plugins/dotnet-diag/skills/microbenchmarking/SKILL.md create mode 100644 plugins/dotnet-diag/skills/microbenchmarking/references/bdn-internals-and-tuning.md create mode 100644 plugins/dotnet-diag/skills/microbenchmarking/references/comparison-strategies.md create mode 100644 plugins/dotnet-diag/skills/microbenchmarking/references/diagnosers-and-exporters.md create mode 100644 plugins/dotnet-diag/skills/microbenchmarking/references/project-setup-and-running.md create mode 100644 plugins/dotnet-diag/skills/microbenchmarking/references/writing-benchmarks.md create mode 100644 tests/dotnet-diag/microbenchmarking/TextAnalyzer/TextAnalyzer.cs create mode 100644 tests/dotnet-diag/microbenchmarking/TextAnalyzer/TextAnalyzer.csproj create mode 100644 tests/dotnet-diag/microbenchmarking/eval.yaml diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 50046be494..0c7c618035 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -52,6 +52,9 @@ /plugins/dotnet-diag/skills/clr-activation-debugging/ @marklio @ChrisAhna @dotnet/skills-diag-reviewers /tests/dotnet-diag/clr-activation-debugging/ @marklio @ChrisAhna @dotnet/skills-diag-reviewers +/plugins/dotnet-diag/skills/microbenchmarking/ @dotnet/dotnet-perf-team @dotnet/skills-diag-reviewers +/tests/dotnet-diag/microbenchmarking/ @dotnet/dotnet-perf-team @dotnet/skills-diag-reviewers + /plugins/dotnet-diag/agents/optimizing-dotnet-performance.agent.md @dotnet/appmodel @dotnet/skills-diag-reviewers /plugins/dotnet/agents/optimizing-dotnet-performance.agent.md @dotnet/appmodel diff --git a/eng/dashboard/generate-token-data.ps1 b/eng/dashboard/generate-token-data.ps1 index 965d5e0fd2..5a0b66b35d 100644 --- a/eng/dashboard/generate-token-data.ps1 +++ b/eng/dashboard/generate-token-data.ps1 @@ -18,7 +18,7 @@ $plugins = [ordered]@{ "dotnet" = @("csharp-scripts", "dotnet-pinvoke", "nuget-trusted-publishing") "dotnet-ai" = @("technology-selection") "dotnet-data" = @("optimizing-ef-core-queries") - "dotnet-diag" = @("analyzing-dotnet-performance", "dotnet-trace-collect", "dump-collect") + "dotnet-diag" = @("analyzing-dotnet-performance", "dotnet-trace-collect", "dump-collect", "microbenchmarking") "dotnet-maui" = @("dotnet-maui-doctor") "dotnet-msbuild" = @("binlog-failure-analysis", "build-parallelism", "build-perf-diagnostics", "incremental-build", "msbuild-modernization") "dotnet-test" = @("migrate-vstest-to-mtp", "run-tests", "writing-mstest-tests") diff --git a/eng/eval-quality/underpowered-allowlist.txt b/eng/eval-quality/underpowered-allowlist.txt index 1da399d04a..7466799646 100644 --- a/eng/eval-quality/underpowered-allowlist.txt +++ b/eng/eval-quality/underpowered-allowlist.txt @@ -28,6 +28,7 @@ tests/dotnet-advanced/csharp-scripts/eval.yaml tests/dotnet-aspnetcore/convert-blazor-server-to-webapp/eval.yaml tests/dotnet-data/optimizing-ef-core-queries/eval.yaml +tests/dotnet-diag/microbenchmarking/eval.yaml tests/dotnet-msbuild/binlog-failure-analysis/eval.yaml tests/dotnet-msbuild/build-parallelism/eval.yaml tests/dotnet-msbuild/build-perf-baseline/eval.yaml diff --git a/plugins/dotnet-diag/skills/microbenchmarking/SKILL.md b/plugins/dotnet-diag/skills/microbenchmarking/SKILL.md new file mode 100644 index 0000000000..9c7817cb03 --- /dev/null +++ b/plugins/dotnet-diag/skills/microbenchmarking/SKILL.md @@ -0,0 +1,137 @@ +--- +name: microbenchmarking +description: > + Activate this skill when BenchmarkDotNet (BDN) is involved in the task — creating, + running, configuring, or reviewing BDN benchmarks. Also activate when + microbenchmarking .NET code would be useful and BenchmarkDotNet is the likely + tool. Consider activating when answering a .NET performance question requires + measurement and BenchmarkDotNet may be needed. + Covers microbenchmark design, BDN configuration and project setup, how to run + BDN microbenchmarks efficiently and effectively, and using BDN for side-by-side + performance comparisons. + Do NOT use for profiling/tracing .NET code (dotnet-trace, PerfView), production + telemetry, or load/stress testing (Crank, k6). +license: MIT +--- + +# Benchmark Authoring Guidelines + +BenchmarkDotNet (BDN) is a .NET library for writing and running microbenchmarks. Throughout this skill, "BDN" refers to BenchmarkDotNet. + +> **Note:** Evaluations of LLMs writing BenchmarkDotNet benchmarks have revealed common failure patterns caused by outdated assumptions about BDN's behavior — particularly around runtime comparison, job configuration, and execution defaults that have changed in recent versions. The reference files in this skill contain verified, current information. **You MUST read the reference files relevant to the task before writing any code** — your training data likely contains outdated or incorrect BDN patterns. + +## Key concepts + +- **Job** — describes how to run a benchmark: runtime, iteration counts, launch count, run strategy, and environment settings. Multiple jobs can be configured to run the same benchmarks under different conditions. +- **Benchmark case** — one method × one parameter combination × one job. The atomic unit BDN measures. +- **Operation** — the logical unit of work being measured. All BDN output columns (Mean, Error, etc.) report time per operation. +- **Invocation** — a single call to the benchmark method. By default, 1 invocation = 1 operation. With `OperationsPerInvoke=N`, each invocation counts as N operations. +- **Iteration** — a timed batch of invocations. BDN measures the total time for all invocations in an iteration, then divides by the total operation count to get per-operation time. + +## Benchmarks are comparative instruments + +A single benchmark number has limited value — it can confirm the order of magnitude of a measurement, but the exact value changes across machines, operating systems, and runtime configurations. Benchmarks produce the most useful information when compared against something. Before writing benchmarks, identify the **comparison axis** for the current task: + +- **Approaches (A vs B)**: comparing alternative implementations side-by-side in the same run. +- **Runtimes**: comparing the same code across .NET versions (e.g., net8.0 vs net9.0). +- **Package versions**: comparing different versions of a NuGet dependency. +- **Builds (before/after)**: comparing a saved DLL of the old code against the current source. +- **Runtime configuration (GC mode, JIT settings)**: understanding how runtime settings affect performance — compared via multiple jobs in a single run. +- **Scale (N=100 vs N=1000)**: understanding how performance changes as input size grows. +- **Hardware/OS**: comparing across different machines or operating systems — requires separate runs on each environment. +- **Historical measurements**: comparing against measurements recorded at a previous point in time. + +BDN can compare the first six axes side-by-side in a single run, but each requires specific CLI flags or configuration that differ from what you might expect — read [references/comparison-strategies.md](references/comparison-strategies.md) for the correct approach for each strategy before configuring a comparison. + +## Use cases and benchmark lifecycle + +There are four distinct reasons a developer writes a benchmark, and each one changes how the benchmark should be designed and where it should live: + +1. **Coverage suite**: Write benchmarks to maximize coverage of real-world usage patterns so that regressions affecting most users are caught. These benchmarks are permanent — they belong in the project's benchmark suite, follow its conventions (directory structure, base classes, naming), and are checked in. + +2. **Issue investigation**: Someone has reported a specific performance problem. Write benchmarks to reproduce and diagnose that specific issue. These benchmarks are task-scoped — they persist across the investigation (reproduce → isolate → verify fix) but are not part of the permanent suite. + +3. **Change validation**: A developer has a PR or change and wants to understand its performance characteristics before merging. These benchmarks are task-scoped — they persist across the review cycle but are not checked in. + +4. **Development feedback**: A developer is actively working on a task and wants to use benchmarks to evaluate approaches and get information early. These benchmarks are task-scoped and throwaway — they persist across the development session but are deleted when the decision is made. + +For use case 1, add to the existing benchmark project following its conventions. For use cases 2–4, create a standalone project in a working directory that persists for the task but is clearly not part of the permanent codebase. + +For **coverage suite** benchmarks, design from the perspective of real callers — what code patterns use this API, what inputs they pass, and what performance characteristics matter to them. Each permanent benchmark should justify its maintenance cost through real-world relevance. For **temporary benchmarks**, keep the case count intentional — each additional test case costs wall-clock time (read [Cost awareness](#cost-awareness)). + +## Cost awareness + +Each benchmark case (one method × one parameter combination × one job) takes **15–25 seconds** with default settings. `[Params]` creates a Cartesian product: two `[Params]` with 3 and 4 values across 5 methods = 60 cases ≈ 20 minutes. Multiple jobs multiply this further. Before running, estimate the total case count and match the job preset to the situation: + +| Preset | Per-case time | When to use | +|--------|--------------|-------------| +| `--job Dry` | <1s | Validate correctness — confirms compilation and execution without measurement | +| `--job Short` | 5–8s | Quick measurements during development or investigation | +| *(default)* | 15–25s | Final measurements for a coverage suite | +| `--job Medium` | 33–52s | Higher confidence when results matter | +| `--job Long` | 3–12 min | High statistical confidence | + +If benchmark runs take longer than expected, results seem unstable, or you need to tune iteration counts or execution settings, read [references/bdn-internals-and-tuning.md](references/bdn-internals-and-tuning.md) for detailed information about BDN's execution pipeline and configuration options. + +## Entry points and configuration + +BDN programs use either **`BenchmarkSwitcher`** (provides interactive benchmark selection for humans, parses CLI arguments) or **`BenchmarkRunner`** (runs specified benchmarks directly). Both support CLI flags like `--filter` and `--runtimes`, but only when `args` is passed through — without it, CLI flags are silently ignored. When using `BenchmarkSwitcher`, always pass `--filter` to avoid hanging on an interactive prompt. + +BDN behavior is customized through **attributes**, **config objects**, and **CLI flags**. + +Read [references/project-setup-and-running.md](references/project-setup-and-running.md) for entry point setup, config object patterns, and CLI flags. If you need to collect data beyond wall-clock time — such as memory allocations, hardware counters, or profiling traces — read [references/diagnosers-and-exporters.md](references/diagnosers-and-exporters.md). + +## Running benchmarks + +BenchmarkDotNet console output is extremely verbose — hundreds of lines per case showing internal calibration, warmup, and measurement details. Redirect all output to a file to avoid consuming context on verbose iteration output: + +``` +dotnet run -c Release -- --filter "*MethodName" --noOverwrite > benchmark.log 2>&1 +``` + +Each benchmark method can take several minutes. Rather than running all benchmarks at once, use `--filter` to run a subset at a time (e.g. one or two methods per invocation), read the results, then run the next subset. This keeps each invocation short — avoiding session or terminal timeouts — and lets you verify results incrementally. Read [references/project-setup-and-running.md](references/project-setup-and-running.md) for filter syntax, CLI flags, and project setup. + +After each run, read the Markdown report (`*-report-github.md`) from the results directory for the summary table. Only read `benchmark.log` if you need to investigate errors or unexpected results. + +## Writing new benchmarks + +### Step 1: Plan the test cases + +Before writing any code, determine: +- Which use case this benchmark serves (coverage, investigation, change validation, or development feedback). +- Which comparison axis applies (what will the number be compared against?). +- What real-world scenarios to benchmark, based on how callers actually use the API. + +Each benchmark case should justify its cost. An uncovered scenario is usually more valuable than another parameter combination for one already covered, but when a specific parameter dimension genuinely affects performance characteristics, the depth is warranted. + +Decide on the list of test cases. For each test case, think through: + +- **How to express variation**: BenchmarkDotNet provides several mechanisms for parameterizing benchmarks — `[Params]` and `[ParamsSource]` for property-level parameters, `[Arguments]` and `[ArgumentsSource]` for method-level arguments, `[ParamsAllValues]` to enumerate all values of a `bool` or enum, and `[GenericTypeArguments]` for varying type parameters on generic benchmark classes. Choose the mechanism that best fits the dimension being varied. Read [references/writing-benchmarks.md](references/writing-benchmarks.md) for the full set of options and correctness patterns. +- **Where input data comes from** — consider which sources are appropriate (these can be combined): + - Hard-coded values — small, fixed values where the exact input matters (e.g., specific strings, known edge-case sizes). Store in fields or `[Params]` to avoid constant folding. + - Asset files — static data that is too large or impractical to embed in source code such as binary blobs. + - Programmatically generated via `[ParamsSource]`/`[ArgumentsSource]`/`[GlobalSetup]` — when data shape matters more than specific content, or when input must be parameterized by size. +- **Whether randomness is appropriate**: If using generated data, use seeded randomness for reproducibility. When generating random data, use a large enough sample that the generated distribution is representative (e.g., 4 random values may cluster in a narrow range, while 1000 will better exercise the full distribution). + +### Step 2: Implement the benchmarks + +For **coverage suite** benchmarks, add to the existing benchmark project and follow its conventions. For **temporary benchmarks** (investigation, change validation, development feedback), create a standalone project — read [references/project-setup-and-running.md](references/project-setup-and-running.md) for project setup and entry point configuration. + +**Adding the BenchmarkDotNet package**: Always use `dotnet add package BenchmarkDotNet` (no version) — this lets NuGet resolve the latest compatible version. Do NOT manually write a `` with a version number into the `.csproj`; BDN versions in training data are outdated and may lack support for current .NET runtimes. + +Write the benchmark code. Follow the patterns in [references/writing-benchmarks.md](references/writing-benchmarks.md) to avoid common measurement errors — in particular: +- **Return results** from benchmark methods to prevent dead code elimination +- **Move initialization to `[GlobalSetup]`** — setup inside the benchmark method is measured; use `[IterationSetup]` only when the benchmark mutates state that must be reset between iterations +- **Do not add manual loops** — BDN controls invocation count automatically +- **Mark a baseline** when comparing alternatives — use `[Benchmark(Baseline = true)]` for method-level comparisons or `.AsBaseline()` on a job for multi-job comparisons so results show relative ratios +- **Store inputs in fields or `[Params]`**, not as literals or `const` values — the JIT can fold constant expressions at compile time, making the benchmark measure a precomputed result instead of the actual computation + +### Step 3: Validate and run + +Validate before committing to a long run: + +1. Run with `--job Dry` first to catch compilation errors and runtime exceptions without spending time on measurement. +2. Run a single representative case with default settings to verify the output looks correct and the numbers are in the expected range. +3. Only run the full suite after validation passes. + +When iterating on benchmark design, use `--job Short` until confident, then switch to default for final numbers. diff --git a/plugins/dotnet-diag/skills/microbenchmarking/references/bdn-internals-and-tuning.md b/plugins/dotnet-diag/skills/microbenchmarking/references/bdn-internals-and-tuning.md new file mode 100644 index 0000000000..41728b867a --- /dev/null +++ b/plugins/dotnet-diag/skills/microbenchmarking/references/bdn-internals-and-tuning.md @@ -0,0 +1,132 @@ +# BenchmarkDotNet Execution and Configuration + +## Build and execution + +BDN generates a standalone project containing the measurement harness, builds it **once per unique build configuration**, and runs each case in its **own process**. Cases are partitioned into separate builds when they differ in factors including runtime, toolchain, platform, JIT, GC settings, build configuration, or MSBuild arguments. All cases sharing the same build configuration share a single build (~5s). + +BDN determines the number of invocations per iteration automatically. + +`[Params]` creates a full Cartesian product: two `[Params]` properties with 3 and 4 values across 5 methods = 3 × 4 × 5 = 60 cases. + +Build overhead (~5s) is paid once regardless of case count. When running cases individually (separate `dotnet run` per case), each pays the build cost, adding ~5s per case. + +## Execution stages per case (default job settings) + +Each case runs through these stages sequentially. Some stage defaults have changed between BDN versions and may change in future releases — check which version of the BenchmarkDotNet NuGet package is installed when the exact behavior matters. + +1. **Process launch + JIT** — The benchmark method is invoked to trigger initial JIT compilation, ensuring the method is compiled before the pilot stage calibrates invocation count. This stage's time is not included in results. +2. **Pilot** — Determines the invocation count per iteration. Fast methods get many invocations per iteration (targeting ~500ms per iteration). Methods slower than ~333ms/op (where two invocations would exceed the target) are fixed at one invocation per iteration. +3. **Warmup** — Adaptive, typically 6–10 iterations for stable benchmarks (those with low variance). During warmup the runtime may further optimize the method (e.g., tiered JIT recompilation). +4. **Actual** — Adaptive, typically 15 iterations for stable benchmarks. Stops when the confidence interval is sufficiently narrow (controlled by `MaxRelativeError`, default 2%). + +**Note (versions before 0.16.0):** prior to BDN 0.16.0, an additional **Overhead** stage ran between Pilot and Warmup by default. It measured the internal invocation loop's own cost and subtracted it from results. Starting in 0.16.0 this stage is off by default and the API to re-enable it (`[EvaluateOverhead]` / `.WithEvaluateOverhead()`) is marked obsolete. + +## Job preset configurations + +| Preset | Per-case time | Warmup | Target iterations | Launch count | Strategy | +|--------|--------------|--------|-------------------|-------------|----------| +| `Dry` | <1s | 0 | 1 | 1 | ColdStart | +| `Short` | 5–8s | 3 | 3 | 1 | Throughput | +| Default | 15–25s | 6–50 (adaptive) | 15–100 (adaptive) | 1 | Throughput | +| `Medium` | 33–52s | 10 | 15 | 2 | Throughput | +| `Long` | 3–12 min | 15 | 100 | 3 | Throughput | + +The `Dry` preset reuses the ColdStart strategy for minimal execution; its purpose is validation (confirming the benchmark compiles and runs), not first-call measurement. + +## Run strategies + +The `RunStrategy` controls how BDN calibrates and measures: + +- **Throughput** (default) — measures steady-state performance. BDN auto-calibrates invocation count via the pilot stage, runs warmup, and adapts iteration count. Use for microbenchmarks. +- **ColdStart** — single invocation per iteration, skips all preliminary stages (JIT pre-trigger, pilot, warmup, overhead). The first measured invocation includes JIT compilation time. Use for startup time evaluation. +- **Monitoring** — single invocation per iteration. Skips JIT pre-trigger, pilot, and overhead stages (like ColdStart), but includes the warmup stage (default 0 iterations, configurable). Use for macrobenchmarks with high variance that don't reach a steady state. + +## Jobs and mutators + +A **job** defines a complete set of run conditions — runtime, iteration counts, launch count, strategy, etc. A benchmark class can have **multiple jobs**, and BDN will run all benchmark methods under each job separately. For example, `[SimpleJob(RuntimeMoniker.Net80)]` and `[SimpleJob(RuntimeMoniker.Net90)]` on the same class runs every method twice — once per runtime. + +A **mutator** is not a standalone job. It is a partial override that gets applied to every existing job. This distinction matters when a class has multiple jobs: + +```csharp +[SimpleJob(RuntimeMoniker.Net80)] // Job A +[SimpleJob(RuntimeMoniker.Net90)] // Job B +[WarmupCount(3)] // Mutator — applied to BOTH Job A and Job B +public class MyBenchmarks { ... } +``` + +Without the mutator distinction, `[WarmupCount(3)]` would be a third job with just a warmup count override and default everything else — probably not what was intended. + +Jobs are resolved by collecting all standard jobs (from `[SimpleJob]`, etc.; `Job.Default` if none), then applying all mutators to every job. CLI flags like `--warmupCount 3` act as mutators — they override that setting on all jobs defined in source code. `--job Short` adds a standard job. + +## Execution-related attributes + +**Class or method level (mutator attributes):** +These override specific job settings. When applied to a method, they affect only that method's cases. When applied to a class, they affect all methods in the class. + +| Attribute | Default | Config (on Job) | CLI flag | +|-----------|---------|----------------|----------| +| `[WarmupCount(N)]` | null (adaptive) | `.WithWarmupCount(N)` | `--warmupCount N` | +| `[IterationCount(N)]` | null (adaptive) | `.WithIterationCount(N)` | `--iterationCount N` | +| `[MinWarmupCount(N)]` | 6 | `.WithMinWarmupCount(N)` | `--minWarmupCount N` | +| `[MaxWarmupCount(N)]` | 50 | `.WithMaxWarmupCount(N)` | `--maxWarmupCount N` | +| `[MinIterationCount(N)]` | 15 | `.WithMinIterationCount(N)` | `--minIterationCount N` | +| `[MaxIterationCount(N)]` | 100 | `.WithMaxIterationCount(N)` | `--maxIterationCount N` | +| `[InvocationCount(N)]` | null (auto pilot) | `.WithInvocationCount(N)` | `--invocationCount N` | +| `[IterationTime(ms)]` | 500ms | `.WithIterationTime(TimeInterval.FromMilliseconds(ms))` | `--iterationTime ms` | +| `[ProcessCount(N)]` | 1 | `.WithLaunchCount(N)` | `--launchCount N` | +| `[MaxRelativeError(pct)]` | 0.02 (= 2%) | `.WithMaxRelativeError(pct)` | — | + +Note: `[ProcessCount]` and `--launchCount` control the same setting (how many separate processes BDN launches per case). The naming differs between API surfaces. + +The `[RunOncePerIteration]` attribute (also available as `.RunOncePerIteration()` or `--runOncePerIteration`) is shorthand for setting `InvocationCount=1` and `UnrollFactor=1`. + +**Note (versions before 0.16.0):** `[EvaluateOverhead(bool)]` / `.WithEvaluateOverhead(bool)` / `--noOverheadEvaluation` controlled overhead subtraction. These are obsolete since 0.16.0 when overhead evaluation was disabled by default. + +**Class or assembly level:** +- Job attributes: `[SimpleJob(...)]`, `[DryJob]`, `[ShortRunJob]`, `[MediumRunJob]`, `[LongRunJob]`, `[VeryLongRunJob]`. AllowMultiple — can stack to run the same benchmarks under different job configurations. + +## Unroll factor + +BDN generates a measurement method that contains the benchmark code repeated `UnrollFactor` times (default 16). This reduces measurement loop overhead relative to the actual work. + +UnrollFactor is distinct from `OperationsPerInvoke`: UnrollFactor is an engine optimization, while `OperationsPerInvoke` is a user declaration that each invocation performs multiple logical operations. + +When `[IterationSetup]` or `[IterationCleanup]` is used, BDN defaults to `UnrollFactor=1` and `InvocationCount=1` so that setup/cleanup runs before and after each single invocation of the benchmark method. Explicitly setting `InvocationCount` or `UnrollFactor` overrides this behavior. + +| Attribute | Config API | CLI flag | +|-----------|------------|----------| +| `[UnrollFactor(N)]` | `.WithUnrollFactor(N)` | `--unrollFactor N` | + +## Execution environment + +The settings below configure the runtime environment the benchmark process runs in. They are orthogonal to the execution pipeline above — they don't change how many iterations run or how the engine measures, they change *what* is being measured. + +| Purpose | Attribute | Config API | CLI flag | +|---------|-----------|------------|----------| +| Target runtimes | `[SimpleJob(RuntimeMoniker.Net80)]` | `Job.Default.WithRuntime(CoreRuntime.Core80)` | `--runtimes net8.0 net9.0` (first is baseline) | +| Environment variables | — | `job.WithEnvironmentVariable("key", "value")` | `--envVars KEY:VALUE` | + +Multiple runtimes multiply the total case count and each requires a separate build. + +### GC configuration + +| Setting | Attribute | Config API | +|---------|-----------|------------| +| Server GC | `[GcServer(true)]` | `.WithGcServer(true)` | +| Concurrent GC | `[GcConcurrent(bool)]` | `.WithGcConcurrent(bool)` | + +### MemoryRandomization + +| Surface | Usage | +|---------|-------| +| Attribute | `[MemoryRandomization]` | +| Config | `.WithMemoryRandomization(true)` | +| CLI | `--memoryRandomization` | + +The `[MemoryRandomization]` attribute causes BDN to allocate random-sized memory between iterations, shifting heap object alignment. This reveals whether benchmark results depend on memory layout (cache line alignment, GC heap position) rather than algorithmic performance. + +When enabled, BDN: +- Allocates random-sized Gen0 and LOH objects between iterations +- Uses `stackalloc` with random size to shift stack alignment +- Re-runs `[GlobalCleanup]` and `[GlobalSetup]` after every iteration +- Disables outlier removal (since multimodal results may be genuine) diff --git a/plugins/dotnet-diag/skills/microbenchmarking/references/comparison-strategies.md b/plugins/dotnet-diag/skills/microbenchmarking/references/comparison-strategies.md new file mode 100644 index 0000000000..f161bd3e6c --- /dev/null +++ b/plugins/dotnet-diag/skills/microbenchmarking/references/comparison-strategies.md @@ -0,0 +1,188 @@ +# Comparing benchmark results + +BenchmarkDotNet can compare multiple implementations or versions in a single run, producing a side-by-side table with ratio columns and statistical analysis. This is generally preferable to separate runs because it controls for environmental variance. + +## Strategy 1: Side-by-side methods (preferred) + +When both the old and new implementations can coexist in the same compilation, define separate benchmark methods: + +```csharp +public class SortBenchmark +{ + private int[] _data; + + [GlobalSetup] + public void Setup() => _data = Enumerable.Range(0, 1000).Reverse().ToArray(); + + [Benchmark(Baseline = true)] + public void BubbleSort() => Sorting.BubbleSort((int[])_data.Clone()); + + [Benchmark] + public void QuickSort() => Sorting.QuickSort((int[])_data.Clone()); +} +``` + +BDN displays a Ratio column showing each method's mean relative to the baseline. This is the simplest approach and should be preferred whenever both implementations are available at compile time. + +## Strategy 2: Comparing runtimes + +To compare the same benchmark across different .NET runtime versions, use `--runtimes` on the command line or configure jobs. The `.csproj` must use `net8.0;net9.0` (plural) listing all targets: + +``` +dotnet run -c Release --framework net9.0 -- --runtimes net8.0 net9.0 +``` + +```csharp +var config = DefaultConfig.Instance + .AddJob(Job.Default.WithRuntime(CoreRuntime.Core80).AsBaseline()) + .AddJob(Job.Default.WithRuntime(CoreRuntime.Core90)); +``` + +Each runtime becomes a separate job. BDN builds separate executables per runtime and shows them side-by-side with ratio columns. + +## Strategy 3: Comparing NuGet package versions + +To compare different versions of a NuGet dependency, use MSBuild properties to control the package version per job. Each job gets a separate build with the specified version. + +**.csproj** — use an MSBuild property for the version: +```xml + + 2.0.0 + + + + +``` + +**Config** — create a job per version: +```csharp +var config = DefaultConfig.Instance + .AddJob(Job.Default + .WithMsBuildArguments("/p:MyLibVersion=1.0.0") + .WithId("v1.0.0") + .AsBaseline()) + .AddJob(Job.Default + .WithMsBuildArguments("/p:MyLibVersion=2.0.0") + .WithId("v2.0.0")); +``` + +All versions must be source-compatible with the benchmark code (same namespace, same method signatures). BDN builds a separate exe per job because `WithArguments` changes the build partition. + +This works with packages from any NuGet source — public registries, private feeds, or local folders created with `dotnet pack`. + +## Strategy 4: Comparing a saved build against current source (DLL reference) + +When the code is not published as a NuGet package but you want to compare before/after a code change, you can save the build output of the baseline version and reference it directly. + +**Step 1** — build and save the baseline: +``` +dotnet build ../MyLib -c Release -o ./saved-baseline +``` + +**Step 2** — make your changes to MyLib. + +**Step 3** — set up the benchmark .csproj with conditional references: +```xml + + + + $(BaselineDll) + + +``` + +**Step 4** — configure two jobs: +```csharp +var config = DefaultConfig.Instance + .AddJob(Job.Default + .WithMsBuildArguments("/p:BaselineDll=../saved-baseline/MyLib.dll") + .WithId("baseline") + .AsBaseline()) + .AddJob(Job.Default + .WithId("current")); +``` + +The `baseline` job builds with a direct DLL reference to the saved output. The `current` job builds with the `ProjectReference` to the current source. BDN produces a side-by-side table with ratio columns. + +This approach works for any class library. The namespace and public API must be the same between the two versions. + +## Strategy 5: Comparing runtime configurations + +To compare how different runtime settings (GC mode, JIT options, PGO) affect performance, define multiple jobs with different environment settings. This works with any `Job` setting — GC mode, environment variables, platform, JIT settings: + +```csharp +// GC mode comparison +var config = DefaultConfig.Instance + .AddJob(Job.Default.WithGcServer(false).WithId("Workstation GC").AsBaseline()) + .AddJob(Job.Default.WithGcServer(true).WithId("Server GC")); + +// JIT setting comparison +var config = DefaultConfig.Instance + .AddJob(Job.Default.WithId("Default").AsBaseline()) + .AddJob(Job.Default.WithEnvironmentVariable("DOTNET_TieredCompilation", "0").WithId("No Tiered")); +``` + +## Strategy 6: Comparing across input scale + +Use `[Params]` on a size property to understand how performance changes with input size. BDN runs each parameter value as a separate case. Geometrically spaced values (e.g., 10×, 100×) help reveal scaling behavior: + +```csharp +[Params(100, 1_000, 10_000)] +public int N; + +private int[] _data; + +[GlobalSetup] +public void Setup() +{ + var rng = new Random(42); + _data = Enumerable.Range(0, N).OrderBy(_ => rng.Next()).ToArray(); +} + +[Benchmark] +public void Sort() => Array.Sort((int[])_data.Clone()); +``` + +## How it works + +All multi-version strategies rely on the same BDN mechanism: + +1. **Build partitioning** — different MSBuild arguments, runtimes, or platform → separate compiled executables. Each case runs in its own process. +2. **Ratio calculation** — when a baseline is marked, BDN adds `Ratio` and `RatioSD` columns. `Ratio` is the mean of current/baseline per-operation time ratios. A `Ratio` of `0.85` means ~15% faster. + +### Marking a baseline + +For side-by-side methods (Strategy 1), mark one method with `[Benchmark(Baseline = true)]`. This compares methods within each job. + +For multi-job strategies (Strategies 2–5), mark one job with `.AsBaseline()` in the config. This compares jobs against each other. For `--runtimes`, the first runtime listed is the baseline. + +These are separate mechanisms — using the wrong one produces no ratio columns. + +Without a baseline, BDN shows absolute numbers only — no ratio columns. + +## Apples-to-apples comparison + +When comparing across jobs (Strategies 2–5), the default behavior runs each job's pilot stage independently, which may choose different invocation counts per job for the same benchmark case. This creates asymmetric measurement conditions that can bias the comparison. + +The `--apples` flag forces symmetric measurement by running in two phases: + +1. **Pilot phase** — BDN runs the baseline job once per benchmark case (method × parameter combination) to determine the invocation count for that case. Different cases get different invocation counts based on their speed. This produces a first results table in the log showing only the baseline with `Ratio = 1.00`. +2. **Measurement phase** — for each benchmark case, ALL jobs run with that case's fixed invocation count, ensuring every job measures the same number of operations per iteration. The final comparison table includes `Ratio` and `InvocationCount` columns and is written to `BenchmarkDotNet.Artifacts/`. + +Outlier removal is disabled in this mode since the controlled setup makes outliers more meaningful. + +``` +dotnet run -c Release --framework net9.0 -- --runtimes net8.0 net9.0 --apples --job short +``` + +Because the pilot runs only once per benchmark case instead of once per job, `--apples` is faster than the default when there are many benchmark cases. The savings grow with the number of methods and parameter combinations. + +Requirements: +- At least two jobs, with exactly one marked as baseline (via `.AsBaseline()` on the job, not `[Benchmark(Baseline = true)]` on the method). When using `--runtimes`, the first runtime listed is automatically treated as the baseline. +- An explicit iteration count, such as by using `--job short` (which sets `IterationCount=3`) or `--iterationCount N`. Adaptive iteration count is disabled in this mode. + +This does not apply to Strategy 1 (side-by-side methods) or Strategy 6 (input scale) because those use a single job — `--apples` requires multiple job objects. + +## Mann-Whitney equivalence test + +BDN can add a `Faster` / `Same` / `Slower` column based on a Mann-Whitney equivalence test. Add it via config: `.AddColumn(StatisticalTestColumn.Create(threshold: "5%"))`. The `threshold` is the equivalence margin — results within that percentage are reported as `Same`. diff --git a/plugins/dotnet-diag/skills/microbenchmarking/references/diagnosers-and-exporters.md b/plugins/dotnet-diag/skills/microbenchmarking/references/diagnosers-and-exporters.md new file mode 100644 index 0000000000..643f74651d --- /dev/null +++ b/plugins/dotnet-diag/skills/microbenchmarking/references/diagnosers-and-exporters.md @@ -0,0 +1,143 @@ +# Measurement and diagnostics + +BenchmarkDotNet measures wall-clock time by default. This reference covers how to collect additional data (allocations, disassembly, hardware counters), customize statistical output, and export results. + +## Diagnosers + +Diagnosers add columns or produce artifacts beyond basic timing. They are enabled via class-level attributes or CLI flags. + +### MemoryDiagnoser + +| Surface | Usage | +|---------|-------| +| Attribute | `[MemoryDiagnoser]` or `[MemoryDiagnoser(displayGenColumns: false)]` | +| Config | `.AddDiagnoser(MemoryDiagnoser.Default)` | +| CLI | `--memory` | + +Tracks managed heap allocations and GC collections per operation. + +Adds columns: `Gen0`, `Gen1`, `Gen2` (GC collections per 1000 operations — a value of `1.0000` means one collection per 1000 operations), `Allocated` (bytes per operation). + +Set `displayGenColumns: false` if only total allocated bytes matter. + +### DisassemblyDiagnoser + +| Surface | Usage | +|---------|-------| +| Attribute | `[DisassemblyDiagnoser(maxDepth: 2)]` | +| Config | `.AddDiagnoser(new DisassemblyDiagnoser(new DisassemblyDiagnoserConfig(maxDepth: 2, printSource: true)))` | +| CLI | `--disasm`, `--disasmDepth N`, `--disasmDiff`, `--disasmFilter "Method*"` | + +Captures the JIT-compiled assembly code for the benchmark method. + +Produces: a per-benchmark disassembly report (exported as GitHub Markdown and/or HTML). + +Config options (`DisassemblyDiagnoserConfig`): +- `maxDepth` (default 1) — how many levels of called methods to include in the disassembly. +- `syntax` — `DisassemblySyntax.Masm` (default), `Intel`, or `Att` +- `printSource` (default false) — include C#/F#/VB source alongside assembly +- `exportDiff` (default false) — when comparing multiple jobs, export a diff view +- `exportCombinedDisassemblyReport` (default false) — all benchmarks in a single HTML report for side-by-side comparison + +When using `printSource: true`, ensure the benchmark project emits PDB files so BDN can map assembly instructions to source lines: + +```xml +pdbonly +true +``` + +### ThreadingDiagnoser + +`[ThreadingDiagnoser]` (CLI: `--threading`, Config: `.AddDiagnoser(ThreadingDiagnoser.Default)`) — adds `Completed Work Items` and `Lock Contentions` columns. + +### EventPipeProfiler + +| Surface | Usage | +|---------|-------| +| Attribute | `[EventPipeProfiler(EventPipeProfile.CpuSampling)]` | +| Config | `.AddDiagnoser(new EventPipeProfiler(EventPipeProfile.CpuSampling))` | +| CLI | `--profiler EP` | + +Collects CPU sampling profiles using .NET's EventPipe infrastructure. Cross-platform. + +Profiles available: `CpuSampling`, `GcVerbose`, `GcCollect`, `Jit`. + +Produces: `.nettrace` and `.speedscope.json` files. By default (attribute/config), runs an extra benchmark iteration dedicated to profiling so timing results are unaffected. + +**CLI note:** `--profiler EP` uses `CpuSampling` with `performExtraBenchmarksRun: false` — profiling is attached to normal measurement runs (no extra iteration, results include profiler overhead, no way to select a different profile). Use the attribute or config API for full control. + +### HardwareCounters (Windows only, requires elevation) + +| Surface | Usage | +|---------|-------| +| Attribute | `[HardwareCounters(HardwareCounter.CacheMisses, HardwareCounter.BranchMispredictions)]` | +| Config | `.AddHardwareCounters(HardwareCounter.CacheMisses, HardwareCounter.BranchMispredictions)` | +| CLI | `--counters CacheMisses+BranchMispredictions` | + +Collects CPU hardware performance counters via ETW. + +Available counters include: `TotalCycles`, `InstructionRetired`, `CacheMisses`, `BranchMispredictions`, `BranchInstructions`, `LlcMisses`, `LlcReference`. + +Requires: Windows, elevated (admin) process, and ETW support. Not available on all hardware. + +## Statistical output + +### Default columns + +| Column | Meaning | +|--------|---------| +| `Mean` | Average per-operation time across all measured iterations | +| `Error` | Half-width of the 99.9% confidence interval — if large relative to Mean, results are noisy | +| `StdDev` | Standard deviation of measurements (hidden when negligible) | +| `Median` | Median per-operation time (auto-shown when data is skewed or median diverges from mean) | +| `P95` | 95th percentile (auto-shown when extreme outliers are present) | +| `Ratio` | Performance relative to the baseline (current / baseline) — only shown when a baseline is marked. A value of `0.85` means ~15% faster. See [comparison-strategies.md](comparison-strategies.md) for how this is calculated | +| `RatioSD` | Standard deviation of the ratio distribution | + +### Adding columns + +Additional statistics can be added via attributes on the benchmark class: + +| Attribute | Column added | +|-----------|-------------| +| `[MedianColumn]` | Median (P50) | +| `[MinColumn]`, `[MaxColumn]` | Minimum, Maximum | +| `[Q1Column]`, `[Q3Column]` | First quartile (P25), Third quartile (P75) | +| `[AllStatisticsColumn]` | Mean, StdErr, StdDev, Ops/s, Min, Q1, Median, Q3, Max | +| `[RankColumn]` | Rank (1, 2, 3...) | +| `[SkewnessColumn]`, `[KurtosisColumn]` | Distribution shape metrics | +| `[OperationsPerSecond]` | Throughput (ops/sec) | + +Percentile columns are available via code: `StatisticColumn.P50`, `StatisticColumn.P85`, `StatisticColumn.P95`, etc. + +### Hiding columns + +Use `[HideColumns]` to remove unwanted columns from the output: + +```csharp +[HideColumns("Error", "StdDev", "RatioSD")] +public class MyBenchmark { ... } +``` + +## Outlier handling + +| Surface | Usage | +|---------|-------| +| Attribute | `[Outliers(OutlierMode.DontRemove)]` | +| Config | `.WithOutlierMode(OutlierMode.DontRemove)` | +| CLI | `--outliers DontRemove` | + +By default, BDN removes upper outliers (unusually slow iterations, typically caused by GC or OS interference). Available modes: `DontRemove`, `RemoveUpper` (default), `RemoveLower`, `RemoveAll`. + +## Export formats + +BDN exports results in multiple formats. By default it produces Markdown and CSV in the `BenchmarkDotNet.Artifacts/results/` directory. + +| Format | Default | Config | CLI flag | +|--------|---------|--------|----------| +| JSON (full, indented) | no | `.AddExporter(JsonExporter.Full)` | `--exporters fulljson` | +| JSON (compressed) | no | `.AddExporter(JsonExporter.Default)` | `--exporters json` | +| CSV | yes | `.AddExporter(CsvExporter.Default)` | `--exporters csv` | +| GitHub Markdown | yes | `.AddExporter(MarkdownExporter.GitHub)` | `--exporters github` | + +Use `JsonExporter.Full` for individual measurements (needed for programmatic comparison). diff --git a/plugins/dotnet-diag/skills/microbenchmarking/references/project-setup-and-running.md b/plugins/dotnet-diag/skills/microbenchmarking/references/project-setup-and-running.md new file mode 100644 index 0000000000..c46ec7dd64 --- /dev/null +++ b/plugins/dotnet-diag/skills/microbenchmarking/references/project-setup-and-running.md @@ -0,0 +1,179 @@ +# Running benchmarks + +This reference covers how to build, run, and read BenchmarkDotNet results. It also covers common CLI flags for controlling output and debugging. + +## Entry points: BenchmarkSwitcher vs BenchmarkRunner + +BenchmarkDotNet programs use one of two entry points. This determines whether CLI arguments work: + +**BenchmarkSwitcher** — passes `args` to BDN, CLI flags work: +```csharp +BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); +BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args, config); // with config +``` + +**BenchmarkRunner** — only forwards args if explicitly passed: +```csharp +BenchmarkRunner.Run(); // CLI flags IGNORED +BenchmarkRunner.Run(args: args); // CLI flags work +BenchmarkRunner.Run(config); // config only, no CLI +BenchmarkRunner.Run(config, args); // both config and CLI +``` + +Before passing CLI flags like `--filter` or `--job`, check which entry point the program uses. If it uses `BenchmarkRunner.Run()` without args, CLI flags will be silently ignored — configuration must be done through attributes and `ManualConfig` instead. + +**Critical**: when `BenchmarkSwitcher` is used, it prompts the user interactively to select which benchmarks to run unless `--filter` is provided. For AI agents, always pass `--filter` to avoid hanging on an interactive prompt. `--filter "*"` matches everything and is the standard way to run all benchmarks non-interactively. + +## Config objects + +Configs can be built in three ways: + +**Modify the default config** — starts with all default loggers, exporters, and columns: +```csharp +var config = DefaultConfig.Instance + .AddJob(Job.Default.WithRuntime(CoreRuntime.Core90)) + .AddDiagnoser(MemoryDiagnoser.Default); +``` + +**Subclass ManualConfig** — useful when config is complex or reused across classes: +```csharp +public class MyConfig : ManualConfig +{ + public MyConfig() + { + AddJob(Job.Default.WithRuntime(CoreRuntime.Core80)); + AddJob(Job.Default.WithRuntime(CoreRuntime.Core90).AsBaseline()); + AddDiagnoser(MemoryDiagnoser.Default); + } +} +``` + +**Start from empty** — `ManualConfig.CreateEmpty()` removes all defaults (no loggers, no exporters, no columns). Use `ManualConfig.CreateMinimumViable()` instead to start with the default columns and console logger. + +Configs can be applied in several ways: + +| Method | Scope | +|--------|-------| +| `BenchmarkRunner.Run(config)` | All benchmarks in the run | +| `BenchmarkSwitcher...Run(args, config)` | All benchmarks in the run | +| `[Config(typeof(MyConfig))]` on class or assembly | That class, or all classes in the assembly | + +## Creating a new benchmark project + +If there is no existing benchmark project to add to, create a new console project with `dotnet new console` and add the BenchmarkDotNet package. Choose a temporary or permanent location based on the scope of the work. + +Use `dotnet add package BenchmarkDotNet` without specifying a version — `dotnet` resolves the latest compatible version automatically. Pinning to a specific version risks missing support for newer runtimes and CLI features. + +**Multi-runtime targeting**: to compare across runtimes (e.g., `--runtimes net8.0 net9.0`), the `.csproj` must use the plural `` property listing all targets: + +```xml +net8.0;net9.0 +``` + +If the project uses the singular `` with only one TFM, multi-runtime runs will fail at build time. + +Then replace `Program.cs` with: +```csharp +using BenchmarkDotNet.Running; + +BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); +``` + +Adjust the `ProjectReference` path to match the project under test. If benchmarking code that isn't in a separate project, skip `dotnet add reference` and put the code under test directly in the benchmark project. + +## Build and run strategy + +BenchmarkDotNet console output is extremely verbose — hundreds of lines per case showing pilot, warmup, and actual iteration details. Redirect all output to a file to avoid consuming context on verbose iteration output. + +**Recommended approach**: build first, then run with output redirected to a file. Always pass `--noOverwrite` so each run writes results to a timestamped subdirectory instead of `BenchmarkDotNet.Artifacts/results/` — without it, each run overwrites the previous results, making it easy to get confused about which run the results are for. + +Each benchmark method can take several minutes. Rather than running all benchmarks at once, use `--filter` to run a subset at a time (e.g. one or two methods per invocation), read the results, then run the next subset. This keeps each invocation short — avoiding session or terminal timeouts — and lets you verify results incrementally. + +``` +dotnet build -c Release +dotnet run -c Release --no-build -- --filter "*MethodName" --noOverwrite > benchmark.log 2>&1 +``` + +After each run, read the Markdown report (`*-report-github.md`) for the summary table. Only read `benchmark.log` if you need to investigate errors or unexpected results. + +## Artifacts directory + +By default, BDN writes to `BenchmarkDotNet.Artifacts/` relative to the working directory. Override with: + +``` +dotnet run -c Release --no-build -- --artifacts ./my-results +``` + +The artifacts directory contains: +``` +BenchmarkDotNet.Artifacts/ +├── MyBenchmark-20240101-120000.log # full console log +└── results/ + ├── MyBenchmark-report-github.md # markdown summary table + └── MyBenchmark-report.csv # CSV data +``` + +Use `--noOverwrite` to prevent overwriting previous results (writes to `BenchmarkDotNet.Artifacts//` instead of `BenchmarkDotNet.Artifacts/results/`). Use `--artifacts` with different paths when comparing results from separate runs. + +## Useful CLI flags for agents + +### Filtering and discovery + +| Flag | Purpose | +|------|---------| +| `--filter "*"` | Run all benchmarks (avoids interactive prompt from BenchmarkSwitcher) | +| `--filter "*.MethodName"` | Run specific benchmark methods | +| `--list flat` | List available benchmark names without running them | +| `--list tree` | List benchmarks in a tree hierarchy | +| `--allCategories ` | Run only benchmarks matching all specified categories | +| `--anyCategories ` | Run benchmarks matching any specified category | + +Tag benchmarks with `[BenchmarkCategory("name")]` (on methods, classes, or assemblies) to enable category-based filtering. + +**How `--filter` works**: BDN matches each pattern against two forms of the benchmark name: +- **Short form**: `Namespace.ClassName.MethodName` (no parameters) +- **Full form**: `Namespace.ClassName.MethodName(param: value, ...)` (includes parameters when present) + +Patterns use glob wildcards (`*` = any characters, `?` = single character), are **case-insensitive**, and must match the **entire** name (anchored). Multiple `--filter` values are OR'd — a case runs if it matches any pattern. + +| Goal | Pattern | +|------|---------| +| Run all benchmarks | `--filter "*"` | +| Run one method by name | `--filter "*MyMethod"` | +| Run all methods in a class | `--filter "*MyClass*"` | +| Run a specific class.method | `--filter "MyNamespace.MyClass.MyMethod"` | +| Same, using wildcard for namespace | `--filter "*MyClass.MyMethod"` | +| Run two specific methods | `--filter "*MethodA" --filter "*MethodB"` | +| Run methods matching a substring | `--filter "*Sort*"` | + +**Tip**: because patterns are anchored, `--filter "MyMethod"` does **not** match `MyNamespace.MyClass.MyMethod` — always use a leading `*` unless matching the short form exactly. Use `--list flat` to see the exact names BDN uses for filtering. + +**Category-based filtering**: tag benchmarks with `[BenchmarkCategory("name")]` on methods, classes, or assemblies to enable category filtering. Categories are inherited — a method tagged `"Parsing"` on a class tagged `"Strings"` has both categories. + +| Flag | Behavior | +|------|----------| +| `--anyCategories Parsing Sorting` | Run benchmarks that have **at least one** of the listed categories | +| `--allCategories Strings Parsing` | Run benchmarks that have **all** of the listed categories | + +When `--filter` and `--allCategories`/`--anyCategories` are used together, a benchmark must satisfy **both** — the glob filter AND the category filter are AND'd together. + +### Output control + +| Flag | Purpose | +|------|---------| +| `--artifacts ./path` | Change where results are written | +| `--noOverwrite` | Don't overwrite previous result files | +| `--exporters json` | Add JSON export (useful for programmatic comparison) | +| `--join` | Combine results from multiple benchmark classes into a single table | +| `--hide "Error" "StdDev"` | Hide specific columns from the results table | +| `--keepFiles` | Keep the generated benchmark project files — useful for debugging build failures | + +## Dry run validation + +Always run `--job Dry` first to catch compilation and runtime errors before committing to a full run: + +``` +dotnet run -c Release --no-build -- --filter "*" --job Dry --noOverwrite +``` + +A dry run executes each case once (<1 second per case) without meaningful measurement. It validates that setup methods work, parameters are valid, and the benchmark compiles and executes. Only after dry validation passes should you run with default or other job presets. diff --git a/plugins/dotnet-diag/skills/microbenchmarking/references/writing-benchmarks.md b/plugins/dotnet-diag/skills/microbenchmarking/references/writing-benchmarks.md new file mode 100644 index 0000000000..586638e9db --- /dev/null +++ b/plugins/dotnet-diag/skills/microbenchmarking/references/writing-benchmarks.md @@ -0,0 +1,296 @@ +# Benchmark authoring techniques + +This reference covers BenchmarkDotNet features and practices for writing correct benchmark methods. Incorrect benchmarks silently produce misleading results — the techniques here prevent common measurement errors. + +## Dead code elimination + +The JIT compiler can eliminate code whose result is never used. If a benchmark method returns `void` and doesn't store its result anywhere observable, the JIT may partially or fully optimize away the computation. + +**Returning a value from the benchmark method prevents this.** When the method has a non-void return type, the JIT cannot prove the result is unused (the call site in BDN's generated harness is opaque to the JIT), so it must preserve the computation: + +```csharp +// Correct — non-void return prevents DCE +[Benchmark] +public int Parse() => int.Parse("12345"); + +// Wrong — void return, JIT may eliminate the call +[Benchmark] +public void Parse() => int.Parse("12345"); +``` + +For benchmarks that must return `void` (e.g., methods with side effects like `Array.Sort`), DCE is not a concern because the operation itself has observable effects. + +For iterating deferred sequences where returning the sequence object doesn't force enumeration, use the `Consumer` class explicitly — see [Deferred execution](#deferred-execution). + +## Setup and cleanup + +### GlobalSetup / GlobalCleanup + +A method marked `[GlobalSetup]` runs once per benchmark case, before all iterations of that case. Use it to allocate buffers, load data, and initialize state that the benchmark reads but does not mutate. + +```csharp +private int[] _array; + +[GlobalSetup] +public void Setup() => _array = Enumerable.Range(0, 1000).ToArray(); + +[Benchmark] +public int Sum() => _array.Sum(); +``` + +Initialization logic inside the benchmark method itself is measured — this is almost never what you want. + +When a class has multiple benchmarks needing different setup, use the `Target` or `Targets` property: + +```csharp +[GlobalSetup(Target = nameof(BenchmarkA))] +public void SetupA() { ... } + +[GlobalSetup(Targets = new[] { nameof(BenchmarkB), nameof(BenchmarkC) })] +public void SetupBC() { ... } +``` + +`[GlobalCleanup]` runs once after all iterations. Use it to dispose resources (files, connections) created during setup. + +**Note**: when `[MemoryRandomization]` is enabled, BDN re-runs `[GlobalCleanup]` and `[GlobalSetup]` after every iteration (overriding the normal once-only behavior). See [references/bdn-internals-and-tuning.md](references/bdn-internals-and-tuning.md) for details. + +### IterationSetup / IterationCleanup + +A method marked `[IterationSetup]` runs before every iteration. Use it only when the benchmark mutates state that must be reset — for example, sorting an array in-place. + +**Critical constraint**: when `[IterationSetup]` or `[IterationCleanup]` is used, BDN defaults to `InvocationCount=1` and `UnrollFactor=1` (unless explicitly overridden). This means the entire iteration is a single invocation, so the operation should be long enough (generally hundreds of milliseconds or more) for a single-invocation measurement to be reliable — with only one invocation, OS scheduling jitter and timer resolution become a significant fraction of the measured time. + +```csharp +[Params(10_000_000)] // large enough for single-invocation measurement +public int Size { get; set; } + +private int[] _data, _scratch; + +[GlobalSetup] +public void Setup() => _data = Enumerable.Range(0, Size).Reverse().ToArray(); + +[IterationSetup] +public void ResetArray() => Array.Copy(_data, _scratch = new int[Size], Size); + +[Benchmark] +public void Sort() => Array.Sort(_scratch); +``` + +**If `[GlobalSetup]` is sufficient, do not use `[IterationSetup]`.** It adds overhead and constrains the measurement. + +## OperationsPerInvoke + +When part of the benchmark setup cannot be moved to `[GlobalSetup]` — typically because it involves a stack-only type like `Span` — use `OperationsPerInvoke` to amortize the setup cost by performing multiple logical operations per invocation. + +```csharp +private byte[] _array = new byte[18]; + +[Benchmark(OperationsPerInvoke = 16)] +public Span Slice() +{ + Span span = new Span(_array); // setup: can't go in GlobalSetup (stack-only) + + // 16 operations, unrolled without a loop + span = span.Slice(1); span = span.Slice(1); span = span.Slice(1); span = span.Slice(1); + span = span.Slice(1); span = span.Slice(1); span = span.Slice(1); span = span.Slice(1); + span = span.Slice(1); span = span.Slice(1); span = span.Slice(1); span = span.Slice(1); + span = span.Slice(1); span = span.Slice(1); span = span.Slice(1); span = span.Slice(1); + + return span; +} +``` + +BDN divides the measured time by `OperationsPerInvoke`, so the reported result reflects a single `Slice` operation with the `Span` creation cost amortized. The operations are manually unrolled (not in a loop) to avoid loop overhead affecting the measurement. + +## Avoiding loops + +BDN determines how many times to invoke the benchmark method per iteration automatically (the pilot stage). Adding a manual loop inside the benchmark is unnecessary and harmful: + +```csharp +// Wrong — manual loop adds loop overhead and hides per-operation variance +[Benchmark] +public int ParseLoop() +{ + int result = 0; + for (int i = 0; i < 1000; i++) + result += int.Parse("12345"); + return result; +} + +// Correct — BDN handles invocation count +[Benchmark] +public int Parse() => int.Parse("12345"); +``` + +The exception is `OperationsPerInvoke` — when per-invocation setup cannot be avoided, repeating the operation inside the method and declaring the count lets BDN divide the result correctly. + +## No side effects + +Benchmarks should be idempotent — running the method N times should produce the same performance characteristics as running it once. A benchmark that grows a list on every invocation violates this: + +```csharp +// Wrong — list grows with every invocation, later calls are slower +List _numbers = new(); + +[Benchmark] +public void Add() => _numbers.Add(12345); +``` + +If the operation inherently mutates state (e.g., `Array.Sort`), use `[IterationSetup]` to reset state between iterations, with input large enough for reliable single-invocation measurement. + +## Async benchmarks + +BDN natively supports benchmark methods that return `Task`, `Task`, `ValueTask`, or `ValueTask`. BDN awaits the result automatically — there is no special attribute or configuration needed: + +```csharp +[Benchmark] +public async Task ReadAsync() +{ + using var stream = new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: true); + var buffer = new byte[4096]; + return await stream.ReadAsync(buffer); +} +``` + +**Async setup/cleanup**: `[GlobalSetup]` and `[GlobalCleanup]` methods can also return `Task` or `ValueTask` — BDN awaits them automatically. `[IterationSetup]` and `[IterationCleanup]` do **not** support async return types; they must be synchronous. + +**When NOT to use async**: if the operation being benchmarked is synchronous, do not wrap it in `async`/`await`. The async state machine adds overhead that would be included in the measurement: + +```csharp +// Wrong — adds async state machine overhead to a synchronous operation +[Benchmark] +public async Task ParseAsync() => await Task.FromResult(int.Parse("12345")); + +// Correct — benchmark the synchronous method directly +[Benchmark] +public int Parse() => int.Parse("12345"); +``` + +## Deferred execution + +Returning `IEnumerable`, `IQueryable`, or `Lazy` from a benchmark measures only the creation of the deferred sequence — not its execution. This is almost always a bug: + +```csharp +// Wrong — measures only the creation of the LINQ query object, not its execution +[Benchmark] +public IEnumerable WhereQuery() => _numbers.Where(n => n > 50); + +// Correct — materialize the result so the query actually executes +[Benchmark] +public List WhereQuery() => _numbers.Where(n => n > 50).ToList(); +``` + +BDN includes a `DeferredExecutionValidator` that detects this mistake and raises a validation error, preventing the benchmark from running. To fix it, either materialize the result (`.ToList()`, `.ToArray()`) or consume it manually using the `.Consume()` extension method: + +```csharp +private Consumer _consumer = new(); + +[Benchmark] +public void WhereQuery() => _numbers.Where(n => n > 50).Consume(_consumer); +``` + +## Constant folding + +The JIT can evaluate expressions at compile time when all inputs are constants or literals. If a benchmark operates on constant inputs, the JIT may fold the computation into a precomputed result, and the benchmark measures nothing: + +```csharp +// Wrong — JIT can compute Math.Sqrt(144.0) at compile time +[Benchmark] +public double Sqrt() => Math.Sqrt(144.0); + +// Correct — field value is not a compile-time constant +private double _value = 144.0; + +[Benchmark] +public double Sqrt() => Math.Sqrt(_value); +``` + +Store inputs in fields, `[Params]`, or `[Arguments]` — never as literals or `const` values in the benchmark method. + +## Randomness and reproducibility + +When benchmarks use generated input data, use a fixed seed so results are comparable across runs: + +```csharp +[GlobalSetup] +public void Setup() +{ + var rng = new Random(42); // fixed seed + _data = new byte[Size]; + rng.NextBytes(_data); +} +``` + +## Benchmark class constraints + +BDN generates source code for a derived type from the benchmark class, which is compiled as part of its generated project. This imposes constraints: +- The class must be `public` +- The class must not be `sealed`, `static`, or `abstract` +- The class must be a `class`, not a `struct` or `ref struct` +- Benchmark methods must be `public` and instance (not `static`) + +## Parameterization summary + +| Feature | Target | Use when | +|---------|--------|----------| +| `[Params]` | Field/Property | Values needed in setup; applies to all benchmarks in the class | +| `[ParamsSource]` | Field/Property | Dynamic or complex values needed in setup | +| `[ParamsAllValues]` | Field/Property | Enum or bool — test every possible value | +| `[Arguments]` | Method | Inline values for a specific benchmark method | +| `[ArgumentsSource]` | Method | Dynamic or complex values for a specific benchmark method | +| `[GenericTypeArguments]` | Class | Vary type parameters (e.g., value type vs reference type) | + +`[Params]` applies to all benchmarks in the class. If different benchmarks need different parameter ranges, split them into separate classes. + +`[Arguments]` and `[ArgumentsSource]` are method-specific and their initialization time is excluded from the measurement. `[ArgumentsSource]` methods return `IEnumerable` for single-parameter benchmarks, or `IEnumerable` for multi-parameter benchmarks (each array is one set of arguments). `[ParamsSource]` methods return `IEnumerable` (each element is a single value assigned to the field/property). + +```csharp +// Single-parameter: IEnumerable +[Benchmark] +[ArgumentsSource(nameof(Inputs))] +public int Parse(string text) => int.Parse(text); + +public IEnumerable Inputs() +{ + yield return "12345"; + yield return "999999999"; + yield return "-42"; +} + +// Multi-parameter: IEnumerable +[Benchmark] +[ArgumentsSource(nameof(Inputs))] +public bool TryParse(string text, NumberStyles style) => int.TryParse(text, style, null, out _); + +public IEnumerable Inputs() +{ + yield return new object[] { "12345", NumberStyles.Integer }; + yield return new object[] { "0xFF", NumberStyles.HexNumber }; +} +``` + +`[ParamsSource]` works the same way but targets a field/property and applies to all benchmarks in the class: + +```csharp +[ParamsSource(nameof(Sizes))] +public int N; + +public IEnumerable Sizes() => new[] { 100, 1_000, 10_000 }; +``` + +`[GenericTypeArguments]` varies type parameters on a generic benchmark class. Each attribute creates a separate closed generic type that BDN runs independently: + +```csharp +[GenericTypeArguments(typeof(int))] +[GenericTypeArguments(typeof(string))] +public class CollectionBenchmark +{ + private List _list; + + [GlobalSetup] + public void Setup() => _list = new List(Enumerable.Repeat(default(T)!, 1000)); + + [Benchmark] + public bool Contains() => _list.Contains(default!); +} +``` diff --git a/tests/dotnet-diag/microbenchmarking/TextAnalyzer/TextAnalyzer.cs b/tests/dotnet-diag/microbenchmarking/TextAnalyzer/TextAnalyzer.cs new file mode 100644 index 0000000000..bb04ae169c --- /dev/null +++ b/tests/dotnet-diag/microbenchmarking/TextAnalyzer/TextAnalyzer.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace TextAnalysis; + +/// +/// Analyzes text content and provides statistical summaries. +/// Pre-computes word metrics on construction for efficient repeated queries. +/// +public class TextAnalyzer +{ + private readonly string[] _words; + private readonly ReadOnlyCollection _wordLengths; + + public TextAnalyzer(string text) + { + ArgumentNullException.ThrowIfNull(text); + _words = text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); + + int[] lengths = new int[_words.Length]; + for (int i = 0; i < _words.Length; i++) + lengths[i] = _words[i].Length; + _wordLengths = new ReadOnlyCollection(lengths); + } + + /// Gets the number of words in the text. + public int WordCount => _words.Length; + + /// Computes the average word length. + public double AverageWordLength() + { + if (_wordLengths.Count == 0) return 0; + int total = 0; + for (int i = 0; i < _wordLengths.Count; i++) + total += _wordLengths[i]; + return (double)total / _wordLengths.Count; + } + + /// + /// Builds a histogram of word lengths. Index i contains the count + /// of words with length i. + /// + public ReadOnlyCollection WordLengthHistogram() + { + int max = 0; + for (int i = 0; i < _wordLengths.Count; i++) + if (_wordLengths[i] > max) max = _wordLengths[i]; + if (max == 0) return new ReadOnlyCollection([]); + int[] histogram = new int[max + 1]; + for (int i = 0; i < _wordLengths.Count; i++) + histogram[_wordLengths[i]]++; + return new ReadOnlyCollection(histogram); + } + + /// Counts the number of unique words (case-insensitive). + public int UniqueWordCount() + { + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (string word in _words) + seen.Add(word); + return seen.Count; + } +} diff --git a/tests/dotnet-diag/microbenchmarking/TextAnalyzer/TextAnalyzer.csproj b/tests/dotnet-diag/microbenchmarking/TextAnalyzer/TextAnalyzer.csproj new file mode 100644 index 0000000000..77e0728a0e --- /dev/null +++ b/tests/dotnet-diag/microbenchmarking/TextAnalyzer/TextAnalyzer.csproj @@ -0,0 +1,7 @@ + + + net9.0 + enable + enable + + diff --git a/tests/dotnet-diag/microbenchmarking/eval.yaml b/tests/dotnet-diag/microbenchmarking/eval.yaml new file mode 100644 index 0000000000..89af6f129d --- /dev/null +++ b/tests/dotnet-diag/microbenchmarking/eval.yaml @@ -0,0 +1,38 @@ +name: microbenchmarking +description: Evaluates the dotnet-diag/microbenchmarking skill +type: capability +config: + timeout: 10m +stimuli: + - name: Investigate runtime upgrade performance impact + prompt: > + Your team is upgrading the codebase from .NET 9 to .NET 10. You have been asked to benchmark AverageWordLength, + WordLengthHistogram, and UniqueWordCount to check how the upgrade will impact their performance. The source code + is in the TextAnalyzer subdirectory (TextAnalyzer.cs and TextAnalyzer.csproj). We don't need anything too + comprehensive, don't spend more than 10 minutes on this. Don't worry about cleaning up any files or projects you + create along the way. Note: this machine may be under load from other processes. If the .NET 9 runtime is missing, + install it using the official dotnet-install script from https://dot.net/v1/dotnet-install.sh (or + dotnet-install.ps1 on Windows). + environment: + files: + - src: . + dest: . + graders: + - type: file-contains + config: + path: "**/*.csproj" + value: BenchmarkDotNet + - type: file-exists + config: + path: "**/*-report*.md" + - type: prompt + rubric: + - "The benchmarks follow best practices: methods return their results to prevent dead code elimination, input data + is stored in fields/properties rather than const or literal values, and initialization/data setup is in a setup + method not inside the benchmark methods" + - The agent let NuGet resolve the BenchmarkDotNet version rather than writing one from memory + - The benchmarks were actually run and completed, producing results that compare .NET 9 vs .NET 10 + - The agent correctly identified that AverageWordLength and WordLengthHistogram got significantly faster on .NET + 10 (expected ~2-3x faster), while UniqueWordCount showed no meaningful change + - The agent completed the task efficiently within the time constraints rather than spending excessive time on + unnecessary iterations or troubleshooting From 9ff288c21ae0c52f9d065e6423ef99b799cac3b4 Mon Sep 17 00:00:00 2001 From: Julia Feng Date: Thu, 30 Jul 2026 16:18:25 -0700 Subject: [PATCH 5/5] Remove stale MAUI eval exemptions --- eng/eval-quality/underpowered-allowlist.txt | 3 --- 1 file changed, 3 deletions(-) diff --git a/eng/eval-quality/underpowered-allowlist.txt b/eng/eval-quality/underpowered-allowlist.txt index 7466799646..0d6814dc51 100644 --- a/eng/eval-quality/underpowered-allowlist.txt +++ b/eng/eval-quality/underpowered-allowlist.txt @@ -69,10 +69,7 @@ tests/dotnet-blazor/use-js-interop/eval.yaml tests/dotnet-experimental/exp-test-maintainability/eval.yaml tests/dotnet-maui/maui-app-lifecycle/eval.yaml tests/dotnet-maui/maui-data-binding/eval.yaml -tests/dotnet-maui/maui-dependency-injection/eval.yaml tests/dotnet-maui/maui-safe-area/eval.yaml -tests/dotnet-maui/maui-shell-navigation/eval.yaml -tests/dotnet-maui/maui-theming/eval.yaml tests/dotnet-template-engine/template-smart-defaults/eval.yaml tests/dotnet-test/find-untested-sources/eval.yaml tests/dotnet-test/generate-testability-wrappers/eval.yaml