diff --git a/plugins/dotnet/skills/dotnet-aot-compat/SKILL.md b/plugins/dotnet/skills/dotnet-aot-compat/SKILL.md new file mode 100644 index 0000000000..16a6675c12 --- /dev/null +++ b/plugins/dotnet/skills/dotnet-aot-compat/SKILL.md @@ -0,0 +1,268 @@ +--- +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. +--- + +# 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/skills/dotnet-aot-compat/references/polyfills.md b/plugins/dotnet/skills/dotnet-aot-compat/references/polyfills.md new file mode 100644 index 0000000000..a577f2e2c6 --- /dev/null +++ b/plugins/dotnet/skills/dotnet-aot-compat/references/polyfills.md @@ -0,0 +1,43 @@ +# 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/tests/dotnet/dotnet-aot-compat/after/.gitignore b/tests/dotnet/dotnet-aot-compat/after/.gitignore new file mode 100644 index 0000000000..cd42ee34e8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/.gitignore @@ -0,0 +1,2 @@ +bin/ +obj/ diff --git a/tests/dotnet/dotnet-aot-compat/after/ArmClient.cs b/tests/dotnet/dotnet-aot-compat/after/ArmClient.cs new file mode 100644 index 0000000000..2993823501 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ArmClient.cs @@ -0,0 +1,315 @@ +// 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/dotnet-aot-compat/after/ArmClientOptions.cs b/tests/dotnet/dotnet-aot-compat/after/ArmClientOptions.cs new file mode 100644 index 0000000000..6b60ffcab6 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ArmClientOptions.cs @@ -0,0 +1,81 @@ +// 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/dotnet-aot-compat/after/ArmCollection.cs b/tests/dotnet/dotnet-aot-compat/after/ArmCollection.cs new file mode 100644 index 0000000000..c3b5b1b084 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ArmCollection.cs @@ -0,0 +1,84 @@ +// 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/dotnet-aot-compat/after/ArmEnvironment.cs b/tests/dotnet/dotnet-aot-compat/after/ArmEnvironment.cs new file mode 100644 index 0000000000..ccd1d5ede9 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ArmEnvironment.cs @@ -0,0 +1,82 @@ +// 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/dotnet-aot-compat/after/ArmOperation.cs b/tests/dotnet/dotnet-aot-compat/after/ArmOperation.cs new file mode 100644 index 0000000000..e7e016f29f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ArmOperation.cs @@ -0,0 +1,116 @@ +// 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/dotnet-aot-compat/after/ArmOperationOfT.cs b/tests/dotnet/dotnet-aot-compat/after/ArmOperationOfT.cs new file mode 100644 index 0000000000..5b23a5d6a7 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ArmOperationOfT.cs @@ -0,0 +1,15 @@ +// 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/dotnet-aot-compat/after/ArmResource.cs b/tests/dotnet/dotnet-aot-compat/after/ArmResource.cs new file mode 100644 index 0000000000..3e5e82e19b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ArmResource.cs @@ -0,0 +1,140 @@ +// 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/dotnet-aot-compat/after/Assets/Profile/2020-09-01-hybrid.json b/tests/dotnet/dotnet-aot-compat/after/Assets/Profile/2020-09-01-hybrid.json new file mode 100644 index 0000000000..d19b2f0667 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Assets/Profile/2020-09-01-hybrid.json @@ -0,0 +1,678 @@ +{ + "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/dotnet-aot-compat/after/Azure.ResourceManager.csproj b/tests/dotnet/dotnet-aot-compat/after/Azure.ResourceManager.csproj new file mode 100644 index 0000000000..a8b3ec55de --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Azure.ResourceManager.csproj @@ -0,0 +1,31 @@ + + + + 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/dotnet-aot-compat/after/AzureStackProfile.cs b/tests/dotnet/dotnet-aot-compat/after/AzureStackProfile.cs new file mode 100644 index 0000000000..09f285c061 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/AzureStackProfile.cs @@ -0,0 +1,14 @@ +// 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/dotnet-aot-compat/after/BicepModelReaderWriterOptions.cs b/tests/dotnet/dotnet-aot-compat/after/BicepModelReaderWriterOptions.cs new file mode 100644 index 0000000000..eaa886e500 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/BicepModelReaderWriterOptions.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/after/CodeGenAttributes.cs b/tests/dotnet/dotnet-aot-compat/after/CodeGenAttributes.cs new file mode 100644 index 0000000000..efc951c129 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/CodeGenAttributes.cs @@ -0,0 +1,65 @@ +// 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/dotnet-aot-compat/after/Common/Custom/Models/ArmPlan.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/ArmPlan.cs new file mode 100644 index 0000000000..35564305f8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/ArmPlan.cs @@ -0,0 +1,95 @@ +// 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/dotnet-aot-compat/after/Common/Custom/Models/ArmSku.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/ArmSku.cs new file mode 100644 index 0000000000..ce20416eb1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/ArmSku.cs @@ -0,0 +1,95 @@ +// 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/dotnet-aot-compat/after/Common/Custom/Models/EncryptionProperties.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/EncryptionProperties.cs new file mode 100644 index 0000000000..a5a35be565 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/EncryptionProperties.cs @@ -0,0 +1,18 @@ +// 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/dotnet-aot-compat/after/Common/Custom/Models/EncryptionStatus.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/EncryptionStatus.cs new file mode 100644 index 0000000000..c1fc8e2bbc --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/EncryptionStatus.cs @@ -0,0 +1,18 @@ +// 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/dotnet-aot-compat/after/Common/Custom/Models/KeyVaultProperties.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/KeyVaultProperties.cs new file mode 100644 index 0000000000..5b49b0341a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/KeyVaultProperties.cs @@ -0,0 +1,18 @@ +// 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/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentity.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentity.Serialization.cs new file mode 100644 index 0000000000..cbc31f23a0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentity.Serialization.cs @@ -0,0 +1,263 @@ +// 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/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentity.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentity.cs new file mode 100644 index 0000000000..96313186cf --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentity.cs @@ -0,0 +1,48 @@ +// 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/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentityType.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentityType.cs new file mode 100644 index 0000000000..7954ef73df --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/ManagedServiceIdentityType.cs @@ -0,0 +1,37 @@ +// 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/dotnet-aot-compat/after/Common/Custom/Models/SystemAssignedServiceIdentity.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/SystemAssignedServiceIdentity.cs new file mode 100644 index 0000000000..e887668292 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/SystemAssignedServiceIdentity.cs @@ -0,0 +1,65 @@ +// 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/dotnet-aot-compat/after/Common/Custom/Models/SystemAssignedServiceIdentityType.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/SystemAssignedServiceIdentityType.cs new file mode 100644 index 0000000000..15fb71110a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/Models/SystemAssignedServiceIdentityType.cs @@ -0,0 +1,17 @@ +// 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/dotnet-aot-compat/after/Common/Custom/ResourceManagerModelFactory.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/ResourceManagerModelFactory.cs new file mode 100644 index 0000000000..c5d2b26469 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Custom/ResourceManagerModelFactory.cs @@ -0,0 +1,25 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Internal/Argument.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Internal/Argument.cs new file mode 100644 index 0000000000..0e6dfdb59a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Internal/Argument.cs @@ -0,0 +1,129 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Internal/BicepSerializationHelpers.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Internal/BicepSerializationHelpers.cs new file mode 100644 index 0000000000..633bf5b166 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Internal/BicepSerializationHelpers.cs @@ -0,0 +1,58 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Internal/ChangeTrackingDictionary.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Internal/ChangeTrackingDictionary.cs new file mode 100644 index 0000000000..3e0457dd83 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Internal/ChangeTrackingDictionary.cs @@ -0,0 +1,167 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Internal/ChangeTrackingList.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Internal/ChangeTrackingList.cs new file mode 100644 index 0000000000..1837046c52 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Internal/ChangeTrackingList.cs @@ -0,0 +1,153 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Internal/ModelSerializationExtensions.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Internal/ModelSerializationExtensions.cs new file mode 100644 index 0000000000..c879f184e7 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Internal/ModelSerializationExtensions.cs @@ -0,0 +1,407 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Internal/Optional.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Internal/Optional.cs new file mode 100644 index 0000000000..c21cb37eee --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Internal/Optional.cs @@ -0,0 +1,51 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Internal/WirePathAttribute.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Internal/WirePathAttribute.cs new file mode 100644 index 0000000000..6a974d2a89 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Internal/WirePathAttribute.cs @@ -0,0 +1,27 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/ArmPlan.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/ArmPlan.Serialization.cs new file mode 100644 index 0000000000..95e2fd6d05 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/ArmPlan.Serialization.cs @@ -0,0 +1,291 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/ArmPlan.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/ArmPlan.cs new file mode 100644 index 0000000000..711ac5f348 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/ArmPlan.cs @@ -0,0 +1,71 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/ArmSku.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/ArmSku.Serialization.cs new file mode 100644 index 0000000000..ee12d1ffab --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/ArmSku.Serialization.cs @@ -0,0 +1,289 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/ArmSku.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/ArmSku.cs new file mode 100644 index 0000000000..4a4de3ba03 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/ArmSku.cs @@ -0,0 +1,65 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/ArmSkuTier.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/ArmSkuTier.Serialization.cs new file mode 100644 index 0000000000..c640e16a48 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/ArmSkuTier.Serialization.cs @@ -0,0 +1,32 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/ArmSkuTier.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/ArmSkuTier.cs new file mode 100644 index 0000000000..4320a2d3b4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/ArmSkuTier.cs @@ -0,0 +1,22 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/AzureResourceManagerContext.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/AzureResourceManagerContext.cs new file mode 100644 index 0000000000..f26fee2f3a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/AzureResourceManagerContext.cs @@ -0,0 +1,19 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/CreatedByType.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/CreatedByType.cs new file mode 100644 index 0000000000..f7a4c34f58 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/CreatedByType.cs @@ -0,0 +1,57 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/EncryptionProperties.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/EncryptionProperties.Serialization.cs new file mode 100644 index 0000000000..bc9ff0979a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/EncryptionProperties.Serialization.cs @@ -0,0 +1,190 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/EncryptionProperties.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/EncryptionProperties.cs new file mode 100644 index 0000000000..5b441bcc81 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/EncryptionProperties.cs @@ -0,0 +1,39 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/EncryptionStatus.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/EncryptionStatus.cs new file mode 100644 index 0000000000..c69242b97c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/EncryptionStatus.cs @@ -0,0 +1,51 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/KeyVaultProperties.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/KeyVaultProperties.Serialization.cs new file mode 100644 index 0000000000..5280cd7b90 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/KeyVaultProperties.Serialization.cs @@ -0,0 +1,198 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/KeyVaultProperties.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/KeyVaultProperties.cs new file mode 100644 index 0000000000..2e92a30cff --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/KeyVaultProperties.cs @@ -0,0 +1,39 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/ManagedServiceIdentityType.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/ManagedServiceIdentityType.cs new file mode 100644 index 0000000000..826953ce1c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/ManagedServiceIdentityType.cs @@ -0,0 +1,57 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/OperationStatusResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/OperationStatusResult.Serialization.cs new file mode 100644 index 0000000000..8afe4c80f4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/OperationStatusResult.Serialization.cs @@ -0,0 +1,407 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/OperationStatusResult.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/OperationStatusResult.cs new file mode 100644 index 0000000000..5a902c73e8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/OperationStatusResult.cs @@ -0,0 +1,79 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/ResourceData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/ResourceData.Serialization.cs new file mode 100644 index 0000000000..1b659410bc --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/ResourceData.Serialization.cs @@ -0,0 +1,41 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/ResourceData.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/ResourceData.cs new file mode 100644 index 0000000000..841b931f44 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/ResourceData.cs @@ -0,0 +1,45 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentity.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentity.Serialization.cs new file mode 100644 index 0000000000..2e420c90b8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentity.Serialization.cs @@ -0,0 +1,210 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentity.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentity.cs new file mode 100644 index 0000000000..f7feea87c2 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentity.cs @@ -0,0 +1,22 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentityType.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentityType.cs new file mode 100644 index 0000000000..ab44e79a42 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/SystemAssignedServiceIdentityType.cs @@ -0,0 +1,51 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/SystemData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/SystemData.Serialization.cs new file mode 100644 index 0000000000..513fa91320 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/SystemData.Serialization.cs @@ -0,0 +1,326 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/SystemData.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/SystemData.cs new file mode 100644 index 0000000000..14d762f3b5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/SystemData.cs @@ -0,0 +1,60 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/TrackedResourceData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/TrackedResourceData.Serialization.cs new file mode 100644 index 0000000000..a6af3ca008 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/TrackedResourceData.Serialization.cs @@ -0,0 +1,35 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/TrackedResourceData.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/TrackedResourceData.cs new file mode 100644 index 0000000000..741469301d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/TrackedResourceData.cs @@ -0,0 +1,50 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/UserAssignedIdentity.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/UserAssignedIdentity.Serialization.cs new file mode 100644 index 0000000000..ad78fdb6bc --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/UserAssignedIdentity.Serialization.cs @@ -0,0 +1,190 @@ +// 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/dotnet-aot-compat/after/Common/Generated/Models/UserAssignedIdentity.cs b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/UserAssignedIdentity.cs new file mode 100644 index 0000000000..727197fddd --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Common/Generated/Models/UserAssignedIdentity.cs @@ -0,0 +1,40 @@ +// 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/dotnet-aot-compat/after/Directory.Build.props b/tests/dotnet/dotnet-aot-compat/after/Directory.Build.props new file mode 100644 index 0000000000..8c119d5413 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Directory.Build.props @@ -0,0 +1,2 @@ + + diff --git a/tests/dotnet/dotnet-aot-compat/after/Directory.Packages.props b/tests/dotnet/dotnet-aot-compat/after/Directory.Packages.props new file mode 100644 index 0000000000..5fc7d2a08a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Directory.Packages.props @@ -0,0 +1,10 @@ + + + true + + + + + + + diff --git a/tests/dotnet/dotnet-aot-compat/after/ExperimentalAttribute.cs b/tests/dotnet/dotnet-aot-compat/after/ExperimentalAttribute.cs new file mode 100644 index 0000000000..9465ac0f52 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ExperimentalAttribute.cs @@ -0,0 +1,60 @@ +// 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/dotnet-aot-compat/after/Extensions/ArmClientBuilderExtensions.cs b/tests/dotnet/dotnet-aot-compat/after/Extensions/ArmClientBuilderExtensions.cs new file mode 100644 index 0000000000..2a6acd69ed --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Extensions/ArmClientBuilderExtensions.cs @@ -0,0 +1,35 @@ +// 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/dotnet-aot-compat/after/GenericOperationSource.cs b/tests/dotnet/dotnet-aot-compat/after/GenericOperationSource.cs new file mode 100644 index 0000000000..3c9c96b456 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/GenericOperationSource.cs @@ -0,0 +1,44 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Custom/HelperSuppressions.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Custom/HelperSuppressions.cs new file mode 100644 index 0000000000..dfe77b4da6 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Custom/HelperSuppressions.cs @@ -0,0 +1,13 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Custom/ManagementGroupResource.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Custom/ManagementGroupResource.cs new file mode 100644 index 0000000000..809c4fff69 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Custom/ManagementGroupResource.cs @@ -0,0 +1,26 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Custom/Models/ManagementGroupNameAvailabilityContent.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Custom/Models/ManagementGroupNameAvailabilityContent.cs new file mode 100644 index 0000000000..a033177eb0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Custom/Models/ManagementGroupNameAvailabilityContent.cs @@ -0,0 +1,18 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Extensions/ArmClient.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Extensions/ArmClient.cs new file mode 100644 index 0000000000..6881f263fc --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Extensions/ArmClient.cs @@ -0,0 +1,39 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Extensions/TenantResource.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Extensions/TenantResource.cs new file mode 100644 index 0000000000..457e521a66 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Extensions/TenantResource.cs @@ -0,0 +1,98 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Internal/WirePathAttribute.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Internal/WirePathAttribute.cs new file mode 100644 index 0000000000..9f3fd65374 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Internal/WirePathAttribute.cs @@ -0,0 +1,27 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupOperationSource.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupOperationSource.cs new file mode 100644 index 0000000000..b7ed659f6a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupOperationSource.cs @@ -0,0 +1,36 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperation.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperation.cs new file mode 100644 index 0000000000..ab650d6389 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperation.cs @@ -0,0 +1,94 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperationOfT.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperationOfT.cs new file mode 100644 index 0000000000..9d8c8c1b70 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperationOfT.cs @@ -0,0 +1,100 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupCollection.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupCollection.cs new file mode 100644 index 0000000000..888276d7e4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupCollection.cs @@ -0,0 +1,688 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupData.Serialization.cs new file mode 100644 index 0000000000..95fa34862f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupData.Serialization.cs @@ -0,0 +1,383 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupData.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupData.cs new file mode 100644 index 0000000000..5b5b364b1d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupData.cs @@ -0,0 +1,92 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupResource.Serialization.cs new file mode 100644 index 0000000000..daf7ad8478 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupResource.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupResource.cs new file mode 100644 index 0000000000..596e9a0bbf --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupResource.cs @@ -0,0 +1,505 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionCollection.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionCollection.cs new file mode 100644 index 0000000000..9f8a56d321 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionCollection.cs @@ -0,0 +1,516 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionData.Serialization.cs new file mode 100644 index 0000000000..40d5766cda --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionData.Serialization.cs @@ -0,0 +1,377 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionData.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionData.cs new file mode 100644 index 0000000000..012a80ff0c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionData.cs @@ -0,0 +1,97 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionResource.Serialization.cs new file mode 100644 index 0000000000..27395325f3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionResource.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionResource.cs new file mode 100644 index 0000000000..084663c338 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ManagementGroupSubscriptionResource.cs @@ -0,0 +1,357 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/CreateManagementGroupDetails.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/CreateManagementGroupDetails.Serialization.cs new file mode 100644 index 0000000000..ef52bc8121 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/CreateManagementGroupDetails.Serialization.cs @@ -0,0 +1,174 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/CreateManagementGroupDetails.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/CreateManagementGroupDetails.cs new file mode 100644 index 0000000000..6cfb0e466c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/CreateManagementGroupDetails.cs @@ -0,0 +1,81 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantData.Serialization.cs new file mode 100644 index 0000000000..b0a653ed4f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantData.Serialization.cs @@ -0,0 +1,318 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantData.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantData.cs new file mode 100644 index 0000000000..b6d4f43ca7 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantData.cs @@ -0,0 +1,82 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantListResult.Serialization.cs new file mode 100644 index 0000000000..debf6320d5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantListResult.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantListResult.cs new file mode 100644 index 0000000000..df6d43351c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantParentGroupInfo.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantParentGroupInfo.Serialization.cs new file mode 100644 index 0000000000..8d94b77a62 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantParentGroupInfo.Serialization.cs @@ -0,0 +1,166 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantParentGroupInfo.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantParentGroupInfo.cs new file mode 100644 index 0000000000..5dd49bf750 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/DescendantParentGroupInfo.cs @@ -0,0 +1,67 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityData.Serialization.cs new file mode 100644 index 0000000000..13036e65da --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityData.Serialization.cs @@ -0,0 +1,686 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityData.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityData.cs new file mode 100644 index 0000000000..08b09466be --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityData.cs @@ -0,0 +1,126 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityListResult.Serialization.cs new file mode 100644 index 0000000000..8d9bf21e83 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityListResult.Serialization.cs @@ -0,0 +1,249 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityListResult.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityListResult.cs new file mode 100644 index 0000000000..64d4927aa3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityListResult.cs @@ -0,0 +1,74 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityPermission.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityPermission.Serialization.cs new file mode 100644 index 0000000000..a83caa1d91 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityPermission.Serialization.cs @@ -0,0 +1,32 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityPermission.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityPermission.cs new file mode 100644 index 0000000000..c7a2a6c4cb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityPermission.cs @@ -0,0 +1,22 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntitySearchOption.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntitySearchOption.cs new file mode 100644 index 0000000000..f4893f29e1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntitySearchOption.cs @@ -0,0 +1,60 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityViewOption.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityViewOption.cs new file mode 100644 index 0000000000..d9b563079f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/EntityViewOption.cs @@ -0,0 +1,57 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.Serialization.cs new file mode 100644 index 0000000000..b55f51fb8d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.cs new file mode 100644 index 0000000000..2b3b56a128 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildInfo.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildInfo.Serialization.cs new file mode 100644 index 0000000000..7ce933f5fc --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildInfo.Serialization.cs @@ -0,0 +1,308 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildInfo.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildInfo.cs new file mode 100644 index 0000000000..57e19925e0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildInfo.cs @@ -0,0 +1,87 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildOptions.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildOptions.Serialization.cs new file mode 100644 index 0000000000..daf08773ac --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildOptions.Serialization.cs @@ -0,0 +1,197 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildOptions.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildOptions.cs new file mode 100644 index 0000000000..fa5796a8fe --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildOptions.cs @@ -0,0 +1,87 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildType.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildType.cs new file mode 100644 index 0000000000..75e6a37c4a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupChildType.cs @@ -0,0 +1,51 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCollectionGetEntitiesOptions.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCollectionGetEntitiesOptions.cs new file mode 100644 index 0000000000..3fc2633c8a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCollectionGetEntitiesOptions.cs @@ -0,0 +1,57 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.Serialization.cs new file mode 100644 index 0000000000..b085a0a218 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.Serialization.cs @@ -0,0 +1,264 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.cs new file mode 100644 index 0000000000..079151fec3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.cs @@ -0,0 +1,98 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupExpandType.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupExpandType.cs new file mode 100644 index 0000000000..6fd33fdd70 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupExpandType.cs @@ -0,0 +1,54 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupInfo.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupInfo.Serialization.cs new file mode 100644 index 0000000000..0428a7dd86 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupInfo.Serialization.cs @@ -0,0 +1,451 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupInfo.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupInfo.cs new file mode 100644 index 0000000000..05985dbcf7 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupInfo.cs @@ -0,0 +1,99 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupListResult.Serialization.cs new file mode 100644 index 0000000000..93f35bd07d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupListResult.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupListResult.cs new file mode 100644 index 0000000000..814cf13d89 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.Serialization.cs new file mode 100644 index 0000000000..f7242a4883 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.Serialization.cs @@ -0,0 +1,144 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.cs new file mode 100644 index 0000000000..cbe681771f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.cs @@ -0,0 +1,67 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.Serialization.cs new file mode 100644 index 0000000000..4b5dae992e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.Serialization.cs @@ -0,0 +1,231 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.cs new file mode 100644 index 0000000000..1c2a592629 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.cs @@ -0,0 +1,76 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.Serialization.cs new file mode 100644 index 0000000000..682fa73fb9 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.Serialization.cs @@ -0,0 +1,28 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.cs new file mode 100644 index 0000000000..71cedf1e26 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.cs @@ -0,0 +1,18 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.Serialization.cs new file mode 100644 index 0000000000..dc28ce4978 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.Serialization.cs @@ -0,0 +1,151 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.cs new file mode 100644 index 0000000000..13e65d6bf7 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.cs @@ -0,0 +1,76 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPatch.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPatch.Serialization.cs new file mode 100644 index 0000000000..b3b7c7b454 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPatch.Serialization.cs @@ -0,0 +1,164 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPatch.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPatch.cs new file mode 100644 index 0000000000..8d3aeabcf3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPatch.cs @@ -0,0 +1,71 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPathElement.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPathElement.Serialization.cs new file mode 100644 index 0000000000..f43d095d7d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPathElement.Serialization.cs @@ -0,0 +1,204 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPathElement.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPathElement.cs new file mode 100644 index 0000000000..83a547b41a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ManagementGroupPathElement.cs @@ -0,0 +1,71 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ParentManagementGroupInfo.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ParentManagementGroupInfo.Serialization.cs new file mode 100644 index 0000000000..83195e73cf --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ParentManagementGroupInfo.Serialization.cs @@ -0,0 +1,238 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ParentManagementGroupInfo.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ParentManagementGroupInfo.cs new file mode 100644 index 0000000000..910a28524a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/Models/ParentManagementGroupInfo.cs @@ -0,0 +1,76 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/ResourceManagerModelFactory.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ResourceManagerModelFactory.cs new file mode 100644 index 0000000000..71c0f3315e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/ResourceManagerModelFactory.cs @@ -0,0 +1,269 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/EntitiesRestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/EntitiesRestOperations.cs new file mode 100644 index 0000000000..e69f3eae1e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/EntitiesRestOperations.cs @@ -0,0 +1,337 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/ManagementGroupSubscriptionsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/ManagementGroupSubscriptionsRestOperations.cs new file mode 100644 index 0000000000..5a9ce3d7e5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/ManagementGroupSubscriptionsRestOperations.cs @@ -0,0 +1,517 @@ +// 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/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/ManagementGroupsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/ManagementGroupsRestOperations.cs new file mode 100644 index 0000000000..f284696f8b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ManagementGroup/Generated/RestOperations/ManagementGroupsRestOperations.cs @@ -0,0 +1,897 @@ +// 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/dotnet-aot-compat/after/Properties/AssemblyInfo.cs b/tests/dotnet/dotnet-aot-compat/after/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000..3a31e4dd1d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +// 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/dotnet-aot-compat/after/ProviderConstants.cs b/tests/dotnet/dotnet-aot-compat/after/ProviderConstants.cs new file mode 100644 index 0000000000..dbce6211e2 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ProviderConstants.cs @@ -0,0 +1,14 @@ +// 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/dotnet-aot-compat/after/RehydrationOperation.cs b/tests/dotnet/dotnet-aot-compat/after/RehydrationOperation.cs new file mode 100644 index 0000000000..7fe620e46e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/RehydrationOperation.cs @@ -0,0 +1,39 @@ +// 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/dotnet-aot-compat/after/RehydrationOperationOfT.cs b/tests/dotnet/dotnet-aot-compat/after/RehydrationOperationOfT.cs new file mode 100644 index 0000000000..21b1298880 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/RehydrationOperationOfT.cs @@ -0,0 +1,42 @@ +// 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/dotnet-aot-compat/after/ResourceManagerExtensions.cs b/tests/dotnet/dotnet-aot-compat/after/ResourceManagerExtensions.cs new file mode 100644 index 0000000000..19a2d39743 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ResourceManagerExtensions.cs @@ -0,0 +1,50 @@ +// 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/dotnet-aot-compat/after/ResourceManagerJsonContext.cs b/tests/dotnet/dotnet-aot-compat/after/ResourceManagerJsonContext.cs new file mode 100644 index 0000000000..c252053234 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/ResourceManagerJsonContext.cs @@ -0,0 +1,37 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/ArmClient.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/ArmClient.cs new file mode 100644 index 0000000000..e26f631cc1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/ArmClient.cs @@ -0,0 +1,26 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/ArmRestApiCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/ArmRestApiCollection.cs new file mode 100644 index 0000000000..25e587549e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/ArmRestApiCollection.cs @@ -0,0 +1,129 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/Extensions/ArmResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Extensions/ArmResource.cs new file mode 100644 index 0000000000..451ced6807 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Extensions/ArmResource.cs @@ -0,0 +1,20 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/FeatureResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/FeatureResource.cs new file mode 100644 index 0000000000..ebfa136947 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/FeatureResource.cs @@ -0,0 +1,26 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/GenericResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/GenericResource.cs new file mode 100644 index 0000000000..7de2f6b25d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/GenericResource.cs @@ -0,0 +1,433 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/GenericResourceCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/GenericResourceCollection.cs new file mode 100644 index 0000000000..ee0a0f75a1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/GenericResourceCollection.cs @@ -0,0 +1,266 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/GenericResourceData.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/GenericResourceData.cs new file mode 100644 index 0000000000..f2bf593f62 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/GenericResourceData.cs @@ -0,0 +1,14 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/HelperSuppressions.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/HelperSuppressions.cs new file mode 100644 index 0000000000..f7cda07595 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/HelperSuppressions.cs @@ -0,0 +1,12 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApi.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApi.Serialization.cs new file mode 100644 index 0000000000..af88ab9534 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApi.Serialization.cs @@ -0,0 +1,159 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApi.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApi.cs new file mode 100644 index 0000000000..164b744651 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApi.cs @@ -0,0 +1,49 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApiListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApiListResult.Serialization.cs new file mode 100644 index 0000000000..ab24d2f204 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApiListResult.Serialization.cs @@ -0,0 +1,40 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApiListResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApiListResult.cs new file mode 100644 index 0000000000..884cd877eb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/ArmRestApiListResult.cs @@ -0,0 +1,32 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/Models/EnforcementMode.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/EnforcementMode.cs new file mode 100644 index 0000000000..ccb5c3feb6 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/EnforcementMode.cs @@ -0,0 +1,20 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/Models/LocationExpanded.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/LocationExpanded.cs new file mode 100644 index 0000000000..e585737abe --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/LocationExpanded.cs @@ -0,0 +1,46 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/Models/LocationMetadata.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/LocationMetadata.cs new file mode 100644 index 0000000000..f266b21d35 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/LocationMetadata.cs @@ -0,0 +1,67 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/Models/ResourcesMoveContent.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/ResourcesMoveContent.cs new file mode 100644 index 0000000000..c63ec6232d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/ResourcesMoveContent.cs @@ -0,0 +1,17 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/Models/ResourcesSku.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/ResourcesSku.cs new file mode 100644 index 0000000000..41b1f3e925 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/ResourcesSku.cs @@ -0,0 +1,14 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/Models/SubResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/SubResource.Serialization.cs new file mode 100644 index 0000000000..c6c9a86519 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/SubResource.Serialization.cs @@ -0,0 +1,112 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/Models/SubResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/SubResource.cs new file mode 100644 index 0000000000..4677811ac4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/SubResource.cs @@ -0,0 +1,36 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/Models/Tag.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/Tag.cs new file mode 100644 index 0000000000..de31694444 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/Tag.cs @@ -0,0 +1,20 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/Models/WritableSubResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/WritableSubResource.Serialization.cs new file mode 100644 index 0000000000..b44b3de3e9 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/WritableSubResource.Serialization.cs @@ -0,0 +1,119 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/Models/WritableSubResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/WritableSubResource.cs new file mode 100644 index 0000000000..105741ada8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/Models/WritableSubResource.cs @@ -0,0 +1,36 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/PolicyAssignmentData.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/PolicyAssignmentData.cs new file mode 100644 index 0000000000..0889491a1a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/PolicyAssignmentData.cs @@ -0,0 +1,48 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/PolicyAssignmentResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/PolicyAssignmentResource.cs new file mode 100644 index 0000000000..b658d222e0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/PolicyAssignmentResource.cs @@ -0,0 +1,96 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/ResourceGroupBuilder.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/ResourceGroupBuilder.cs new file mode 100644 index 0000000000..22cc3f1726 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/ResourceGroupBuilder.cs @@ -0,0 +1,133 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/ResourceGroupCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/ResourceGroupCollection.cs new file mode 100644 index 0000000000..cf7e8bb395 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/ResourceGroupCollection.cs @@ -0,0 +1,39 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/ResourceGroupResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/ResourceGroupResource.cs new file mode 100644 index 0000000000..75c02571f4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/ResourceGroupResource.cs @@ -0,0 +1,110 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/ResourceManagerModelFactory.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/ResourceManagerModelFactory.cs new file mode 100644 index 0000000000..73d3cdd844 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/ResourceManagerModelFactory.cs @@ -0,0 +1,42 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/ResourceProviderCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/ResourceProviderCollection.cs new file mode 100644 index 0000000000..c883e46b6d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/ResourceProviderCollection.cs @@ -0,0 +1,152 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/ResourceProviderData.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/ResourceProviderData.cs new file mode 100644 index 0000000000..7081df7c19 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/ResourceProviderData.cs @@ -0,0 +1,63 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/ResourceProviderResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/ResourceProviderResource.cs new file mode 100644 index 0000000000..d31340bbca --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/ResourceProviderResource.cs @@ -0,0 +1,19 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/RestOperations/RestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/RestOperations/RestOperations.cs new file mode 100644 index 0000000000..9652d2393f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/RestOperations/RestOperations.cs @@ -0,0 +1,107 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/RestOperations/TenantsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/RestOperations/TenantsRestOperations.cs new file mode 100644 index 0000000000..a04a4128ac --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/RestOperations/TenantsRestOperations.cs @@ -0,0 +1,19 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/SubscriptionData.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/SubscriptionData.cs new file mode 100644 index 0000000000..01db245a68 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/SubscriptionData.cs @@ -0,0 +1,18 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/SubscriptionResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/SubscriptionResource.cs new file mode 100644 index 0000000000..db043c39c0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/SubscriptionResource.cs @@ -0,0 +1,118 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/TagResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/TagResource.cs new file mode 100644 index 0000000000..a8e6740e55 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/TagResource.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/TenantCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/TenantCollection.cs new file mode 100644 index 0000000000..9a4f57e413 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/TenantCollection.cs @@ -0,0 +1,28 @@ +// 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/dotnet-aot-compat/after/Resources/Custom/TenantResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/TenantResource.cs new file mode 100644 index 0000000000..6fadc0c833 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Custom/TenantResource.cs @@ -0,0 +1,137 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestCollection.cs new file mode 100644 index 0000000000..3d94174f1d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestCollection.cs @@ -0,0 +1,396 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestData.Serialization.cs new file mode 100644 index 0000000000..fd2f9189ee --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestData.Serialization.cs @@ -0,0 +1,647 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestData.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestData.cs new file mode 100644 index 0000000000..32ace96c4d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestData.cs @@ -0,0 +1,117 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestResource.Serialization.cs new file mode 100644 index 0000000000..6c713c5dfe --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestResource.cs new file mode 100644 index 0000000000..62e06308fa --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/DataPolicyManifestResource.cs @@ -0,0 +1,168 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Extensions/ArmClient.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Extensions/ArmClient.cs new file mode 100644 index 0000000000..611e8d348a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Extensions/ArmClient.cs @@ -0,0 +1,183 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Extensions/ArmResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Extensions/ArmResource.cs new file mode 100644 index 0000000000..a70590323b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Extensions/ArmResource.cs @@ -0,0 +1,156 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Extensions/ManagementGroupResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Extensions/ManagementGroupResource.cs new file mode 100644 index 0000000000..2e6a3a5047 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Extensions/ManagementGroupResource.cs @@ -0,0 +1,156 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/FeatureCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/FeatureCollection.cs new file mode 100644 index 0000000000..a0c55991a2 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/FeatureCollection.cs @@ -0,0 +1,394 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/FeatureData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/FeatureData.Serialization.cs new file mode 100644 index 0000000000..6accda525b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/FeatureData.Serialization.cs @@ -0,0 +1,244 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/FeatureData.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/FeatureData.cs new file mode 100644 index 0000000000..ef7d2ec42c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/FeatureData.cs @@ -0,0 +1,81 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/FeatureResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/FeatureResource.Serialization.cs new file mode 100644 index 0000000000..264d1675fc --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/FeatureResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/FeatureResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/FeatureResource.cs new file mode 100644 index 0000000000..463ada11d3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/FeatureResource.cs @@ -0,0 +1,316 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/GenericResourceData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/GenericResourceData.Serialization.cs new file mode 100644 index 0000000000..2dca8040b9 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/GenericResourceData.Serialization.cs @@ -0,0 +1,609 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/GenericResourceData.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/GenericResourceData.cs new file mode 100644 index 0000000000..1440e3dc01 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/GenericResourceData.cs @@ -0,0 +1,121 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Internal/Utf8JsonRequestContent.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Internal/Utf8JsonRequestContent.cs new file mode 100644 index 0000000000..c0ffe14923 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Internal/Utf8JsonRequestContent.cs @@ -0,0 +1,55 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Internal/WirePathAttribute.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Internal/WirePathAttribute.cs new file mode 100644 index 0000000000..4b7cb3247b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Internal/WirePathAttribute.cs @@ -0,0 +1,27 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/GenericResourceOperationSource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/GenericResourceOperationSource.cs new file mode 100644 index 0000000000..f8b70fafa0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/GenericResourceOperationSource.cs @@ -0,0 +1,36 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourceGroupExportResultOperationSource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourceGroupExportResultOperationSource.cs new file mode 100644 index 0000000000..a2603f1e90 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourceGroupExportResultOperationSource.cs @@ -0,0 +1,30 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourcesArmOperation.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourcesArmOperation.cs new file mode 100644 index 0000000000..92e96135b2 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourcesArmOperation.cs @@ -0,0 +1,94 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourcesArmOperationOfT.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourcesArmOperationOfT.cs new file mode 100644 index 0000000000..d9c3f6e3bc --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/ResourcesArmOperationOfT.cs @@ -0,0 +1,103 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/TagResourceOperationSource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/TagResourceOperationSource.cs new file mode 100644 index 0000000000..452c0702a4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/LongRunningOperation/TagResourceOperationSource.cs @@ -0,0 +1,36 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionCollection.cs new file mode 100644 index 0000000000..a11c7b1d4d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionCollection.cs @@ -0,0 +1,501 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionResource.Serialization.cs new file mode 100644 index 0000000000..867c419838 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionResource.cs new file mode 100644 index 0000000000..f254f2ed5e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicyDefinitionResource.cs @@ -0,0 +1,354 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionCollection.cs new file mode 100644 index 0000000000..e556e58ffa --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionCollection.cs @@ -0,0 +1,501 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionResource.Serialization.cs new file mode 100644 index 0000000000..60c244d59e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionResource.cs new file mode 100644 index 0000000000..4f8ffed49d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementGroupPolicySetDefinitionResource.cs @@ -0,0 +1,354 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ManagementLockCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementLockCollection.cs new file mode 100644 index 0000000000..bb744b2095 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementLockCollection.cs @@ -0,0 +1,488 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ManagementLockData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementLockData.Serialization.cs new file mode 100644 index 0000000000..3966a819f8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementLockData.Serialization.cs @@ -0,0 +1,334 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ManagementLockData.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementLockData.cs new file mode 100644 index 0000000000..64c9e5d2cd --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementLockData.cs @@ -0,0 +1,94 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ManagementLockResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementLockResource.Serialization.cs new file mode 100644 index 0000000000..3dfbf0b23b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementLockResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ManagementLockResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementLockResource.cs new file mode 100644 index 0000000000..e02de890dd --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ManagementLockResource.cs @@ -0,0 +1,353 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ApiProfile.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ApiProfile.Serialization.cs new file mode 100644 index 0000000000..0410aa5914 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ApiProfile.Serialization.cs @@ -0,0 +1,204 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ApiProfile.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ApiProfile.cs new file mode 100644 index 0000000000..f739455520 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ApiProfile.cs @@ -0,0 +1,71 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameter.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameter.Serialization.cs new file mode 100644 index 0000000000..4c4698f06a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameter.Serialization.cs @@ -0,0 +1,306 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameter.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameter.cs new file mode 100644 index 0000000000..9eb8280256 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameter.cs @@ -0,0 +1,140 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterType.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterType.cs new file mode 100644 index 0000000000..c0dee9c68a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterType.cs @@ -0,0 +1,66 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterValue.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterValue.Serialization.cs new file mode 100644 index 0000000000..f2827a191a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterValue.Serialization.cs @@ -0,0 +1,173 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterValue.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterValue.cs new file mode 100644 index 0000000000..0e055d7eb1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ArmPolicyParameterValue.cs @@ -0,0 +1,95 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/AvailabilityZoneMappings.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/AvailabilityZoneMappings.Serialization.cs new file mode 100644 index 0000000000..098c56da1e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/AvailabilityZoneMappings.Serialization.cs @@ -0,0 +1,204 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/AvailabilityZoneMappings.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/AvailabilityZoneMappings.cs new file mode 100644 index 0000000000..98f10092e5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/AvailabilityZoneMappings.cs @@ -0,0 +1,71 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/AzureRoleDefinition.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/AzureRoleDefinition.Serialization.cs new file mode 100644 index 0000000000..15d4b4ed84 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/AzureRoleDefinition.Serialization.cs @@ -0,0 +1,351 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/AzureRoleDefinition.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/AzureRoleDefinition.cs new file mode 100644 index 0000000000..f770872147 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/AzureRoleDefinition.cs @@ -0,0 +1,88 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.Serialization.cs new file mode 100644 index 0000000000..701b67d02c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.Serialization.cs @@ -0,0 +1,293 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.cs new file mode 100644 index 0000000000..4f66f5b04c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.cs @@ -0,0 +1,83 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestEffect.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestEffect.Serialization.cs new file mode 100644 index 0000000000..7bee36daad --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestEffect.Serialization.cs @@ -0,0 +1,207 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestEffect.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestEffect.cs new file mode 100644 index 0000000000..140fcae664 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestEffect.cs @@ -0,0 +1,100 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestListResult.Serialization.cs new file mode 100644 index 0000000000..fb372a4e0a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestListResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestListResult.cs new file mode 100644 index 0000000000..769a87638b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/DataPolicyManifestListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/EnforcementMode.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/EnforcementMode.cs new file mode 100644 index 0000000000..239bc9da67 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/EnforcementMode.cs @@ -0,0 +1,51 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ExportTemplate.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ExportTemplate.Serialization.cs new file mode 100644 index 0000000000..491a31fce0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ExportTemplate.Serialization.cs @@ -0,0 +1,154 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ExportTemplate.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ExportTemplate.cs new file mode 100644 index 0000000000..43ce04a802 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ExportTemplate.cs @@ -0,0 +1,72 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocation.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocation.Serialization.cs new file mode 100644 index 0000000000..d3763ccf2d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocation.Serialization.cs @@ -0,0 +1,194 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocation.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocation.cs new file mode 100644 index 0000000000..c052d4f1e8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocation.cs @@ -0,0 +1,39 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocationType.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocationType.cs new file mode 100644 index 0000000000..76cfe6ccdb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ExtendedLocationType.cs @@ -0,0 +1,48 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/FeatureOperationsListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/FeatureOperationsListResult.Serialization.cs new file mode 100644 index 0000000000..82ef256728 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/FeatureOperationsListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/FeatureOperationsListResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/FeatureOperationsListResult.cs new file mode 100644 index 0000000000..e2063f4235 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/FeatureOperationsListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/FeatureProperties.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/FeatureProperties.Serialization.cs new file mode 100644 index 0000000000..8ee5c29a9b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/FeatureProperties.Serialization.cs @@ -0,0 +1,170 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/FeatureProperties.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/FeatureProperties.cs new file mode 100644 index 0000000000..bab8758f08 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/FeatureProperties.cs @@ -0,0 +1,66 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/LocationExpanded.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/LocationExpanded.Serialization.cs new file mode 100644 index 0000000000..9e24d82634 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/LocationExpanded.Serialization.cs @@ -0,0 +1,409 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/LocationExpanded.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/LocationExpanded.cs new file mode 100644 index 0000000000..60e4a76f90 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/LocationExpanded.cs @@ -0,0 +1,102 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/LocationListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/LocationListResult.Serialization.cs new file mode 100644 index 0000000000..570045b6f2 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/LocationListResult.Serialization.cs @@ -0,0 +1,185 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/LocationListResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/LocationListResult.cs new file mode 100644 index 0000000000..a614638e72 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/LocationListResult.cs @@ -0,0 +1,66 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/LocationMetadata.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/LocationMetadata.Serialization.cs new file mode 100644 index 0000000000..df28d93fb8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/LocationMetadata.Serialization.cs @@ -0,0 +1,443 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/LocationMetadata.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/LocationMetadata.cs new file mode 100644 index 0000000000..4fe985db7d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/LocationMetadata.cs @@ -0,0 +1,101 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/LocationType.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/LocationType.Serialization.cs new file mode 100644 index 0000000000..95769ed54d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/LocationType.Serialization.cs @@ -0,0 +1,28 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/LocationType.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/LocationType.cs new file mode 100644 index 0000000000..fe985afe37 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/LocationType.cs @@ -0,0 +1,18 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ManagedByTenant.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ManagedByTenant.Serialization.cs new file mode 100644 index 0000000000..7e0477da19 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ManagedByTenant.Serialization.cs @@ -0,0 +1,166 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ManagedByTenant.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ManagedByTenant.cs new file mode 100644 index 0000000000..17afaec3ad --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ManagedByTenant.cs @@ -0,0 +1,66 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockLevel.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockLevel.cs new file mode 100644 index 0000000000..f3f6fa4cf8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockLevel.cs @@ -0,0 +1,54 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockListResult.Serialization.cs new file mode 100644 index 0000000000..5bb5c7ed46 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockListResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockListResult.cs new file mode 100644 index 0000000000..7702747e45 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockOwner.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockOwner.Serialization.cs new file mode 100644 index 0000000000..aa2bec2bd9 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockOwner.Serialization.cs @@ -0,0 +1,170 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockOwner.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockOwner.cs new file mode 100644 index 0000000000..7cb1045193 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ManagementLockOwner.cs @@ -0,0 +1,66 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/NonComplianceMessage.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/NonComplianceMessage.Serialization.cs new file mode 100644 index 0000000000..92a04db6d4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/NonComplianceMessage.Serialization.cs @@ -0,0 +1,201 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/NonComplianceMessage.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/NonComplianceMessage.cs new file mode 100644 index 0000000000..a412852eaa --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/NonComplianceMessage.cs @@ -0,0 +1,81 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PairedRegion.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PairedRegion.Serialization.cs new file mode 100644 index 0000000000..5e20e69ed5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PairedRegion.Serialization.cs @@ -0,0 +1,238 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PairedRegion.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PairedRegion.cs new file mode 100644 index 0000000000..b4e30a1a8f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PairedRegion.cs @@ -0,0 +1,76 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ParameterDefinitionsValueMetadata.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ParameterDefinitionsValueMetadata.Serialization.cs new file mode 100644 index 0000000000..f90e74ef9a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ParameterDefinitionsValueMetadata.Serialization.cs @@ -0,0 +1,263 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ParameterDefinitionsValueMetadata.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ParameterDefinitionsValueMetadata.cs new file mode 100644 index 0000000000..96ed7496b1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ParameterDefinitionsValueMetadata.cs @@ -0,0 +1,82 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/Permission.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/Permission.Serialization.cs new file mode 100644 index 0000000000..fe7d724800 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/Permission.Serialization.cs @@ -0,0 +1,381 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/Permission.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/Permission.cs new file mode 100644 index 0000000000..0b614bc2dd --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/Permission.cs @@ -0,0 +1,85 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentListResult.Serialization.cs new file mode 100644 index 0000000000..6e769e9894 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentListResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentListResult.cs new file mode 100644 index 0000000000..2c650f257a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentPatch.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentPatch.Serialization.cs new file mode 100644 index 0000000000..098c4203f5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentPatch.Serialization.cs @@ -0,0 +1,214 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentPatch.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentPatch.cs new file mode 100644 index 0000000000..d85c3fcbad --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyAssignmentPatch.cs @@ -0,0 +1,85 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionGroup.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionGroup.Serialization.cs new file mode 100644 index 0000000000..dfd1925207 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionGroup.Serialization.cs @@ -0,0 +1,309 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionGroup.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionGroup.cs new file mode 100644 index 0000000000..9f18d09866 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionGroup.cs @@ -0,0 +1,96 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionListResult.Serialization.cs new file mode 100644 index 0000000000..34758a66f0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionListResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionListResult.cs new file mode 100644 index 0000000000..c09165e0d9 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionReference.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionReference.Serialization.cs new file mode 100644 index 0000000000..dbbf48365e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionReference.Serialization.cs @@ -0,0 +1,313 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionReference.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionReference.cs new file mode 100644 index 0000000000..da023f91ac --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyDefinitionReference.cs @@ -0,0 +1,93 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverride.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverride.Serialization.cs new file mode 100644 index 0000000000..71ce671e03 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverride.Serialization.cs @@ -0,0 +1,249 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverride.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverride.cs new file mode 100644 index 0000000000..d546bbcfa3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverride.cs @@ -0,0 +1,77 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverrideKind.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverrideKind.cs new file mode 100644 index 0000000000..1529755b23 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyOverrideKind.cs @@ -0,0 +1,48 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PolicySetDefinitionListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicySetDefinitionListResult.Serialization.cs new file mode 100644 index 0000000000..87f0ac4fc5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicySetDefinitionListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PolicySetDefinitionListResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicySetDefinitionListResult.cs new file mode 100644 index 0000000000..7077003141 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicySetDefinitionListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PolicyType.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyType.cs new file mode 100644 index 0000000000..9f88c1c72e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PolicyType.cs @@ -0,0 +1,57 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTag.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTag.Serialization.cs new file mode 100644 index 0000000000..07840949b9 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTag.Serialization.cs @@ -0,0 +1,283 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTag.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTag.cs new file mode 100644 index 0000000000..a929577cd8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTag.cs @@ -0,0 +1,82 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagCount.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagCount.Serialization.cs new file mode 100644 index 0000000000..2cd1a8683b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagCount.Serialization.cs @@ -0,0 +1,200 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagCount.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagCount.cs new file mode 100644 index 0000000000..b7d6360ac8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagCount.cs @@ -0,0 +1,71 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagValue.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagValue.Serialization.cs new file mode 100644 index 0000000000..9c1f4d002c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagValue.Serialization.cs @@ -0,0 +1,234 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagValue.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagValue.cs new file mode 100644 index 0000000000..7c91e6cc59 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagValue.cs @@ -0,0 +1,76 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagsListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagsListResult.Serialization.cs new file mode 100644 index 0000000000..bea1bd024f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagsListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagsListResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagsListResult.cs new file mode 100644 index 0000000000..dc4cc163ff --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/PredefinedTagsListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ProviderAuthorizationConsentState.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderAuthorizationConsentState.cs new file mode 100644 index 0000000000..70a7ad1aa3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderAuthorizationConsentState.cs @@ -0,0 +1,57 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ProviderConsentDefinition.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderConsentDefinition.Serialization.cs new file mode 100644 index 0000000000..71de2d86a9 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderConsentDefinition.Serialization.cs @@ -0,0 +1,133 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ProviderConsentDefinition.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderConsentDefinition.cs new file mode 100644 index 0000000000..92b4c29858 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderConsentDefinition.cs @@ -0,0 +1,66 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ProviderExtendedLocation.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderExtendedLocation.Serialization.cs new file mode 100644 index 0000000000..d1b0f54781 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderExtendedLocation.Serialization.cs @@ -0,0 +1,262 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ProviderExtendedLocation.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderExtendedLocation.cs new file mode 100644 index 0000000000..3b129aeeb0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderExtendedLocation.cs @@ -0,0 +1,78 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermission.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermission.Serialization.cs new file mode 100644 index 0000000000..ce8f48ce4a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermission.Serialization.cs @@ -0,0 +1,260 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermission.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermission.cs new file mode 100644 index 0000000000..b8dbd24538 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermission.cs @@ -0,0 +1,81 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermissionListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermissionListResult.Serialization.cs new file mode 100644 index 0000000000..b4082c199c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermissionListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermissionListResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermissionListResult.cs new file mode 100644 index 0000000000..bfb5b6bbb2 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderPermissionListResult.cs @@ -0,0 +1,72 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ProviderRegistrationContent.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderRegistrationContent.Serialization.cs new file mode 100644 index 0000000000..616d8a93e7 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderRegistrationContent.Serialization.cs @@ -0,0 +1,133 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ProviderRegistrationContent.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderRegistrationContent.cs new file mode 100644 index 0000000000..92eb16dbd6 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderRegistrationContent.cs @@ -0,0 +1,77 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceType.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceType.Serialization.cs new file mode 100644 index 0000000000..47c4501434 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceType.Serialization.cs @@ -0,0 +1,627 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceType.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceType.cs new file mode 100644 index 0000000000..64234b3ba9 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceType.cs @@ -0,0 +1,118 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceTypeListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceTypeListResult.Serialization.cs new file mode 100644 index 0000000000..0b206fd01f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceTypeListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceTypeListResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceTypeListResult.cs new file mode 100644 index 0000000000..e58854a89d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ProviderResourceTypeListResult.cs @@ -0,0 +1,72 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/RegionCategory.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/RegionCategory.cs new file mode 100644 index 0000000000..4f94df158a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/RegionCategory.cs @@ -0,0 +1,54 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/RegionType.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/RegionType.cs new file mode 100644 index 0000000000..b78f1316be --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/RegionType.cs @@ -0,0 +1,51 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupExportResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupExportResult.Serialization.cs new file mode 100644 index 0000000000..c6b32ddbe6 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupExportResult.Serialization.cs @@ -0,0 +1,203 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupExportResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupExportResult.cs new file mode 100644 index 0000000000..b6a5fd70bd --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupExportResult.cs @@ -0,0 +1,100 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupListResult.Serialization.cs new file mode 100644 index 0000000000..d618fa828a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupListResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupListResult.cs new file mode 100644 index 0000000000..aad563b999 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupPatch.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupPatch.Serialization.cs new file mode 100644 index 0000000000..c8ee490aac --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupPatch.Serialization.cs @@ -0,0 +1,181 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupPatch.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupPatch.cs new file mode 100644 index 0000000000..b10e558b03 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupPatch.cs @@ -0,0 +1,88 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupProperties.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupProperties.Serialization.cs new file mode 100644 index 0000000000..c364b7d06c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupProperties.Serialization.cs @@ -0,0 +1,170 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupProperties.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupProperties.cs new file mode 100644 index 0000000000..b62fad0a7f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceGroupProperties.cs @@ -0,0 +1,66 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceListResult.Serialization.cs new file mode 100644 index 0000000000..1c5d2308b6 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceListResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceListResult.cs new file mode 100644 index 0000000000..6d1d19e150 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationContent.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationContent.Serialization.cs new file mode 100644 index 0000000000..928c6e4959 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationContent.Serialization.cs @@ -0,0 +1,134 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationContent.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationContent.cs new file mode 100644 index 0000000000..e3886a6c2f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationContent.cs @@ -0,0 +1,84 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationResult.Serialization.cs new file mode 100644 index 0000000000..96c45266ff --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationResult.Serialization.cs @@ -0,0 +1,230 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationResult.cs new file mode 100644 index 0000000000..7e0501f862 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationResult.cs @@ -0,0 +1,77 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationStatus.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationStatus.cs new file mode 100644 index 0000000000..78a1b378f1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceNameValidationStatus.cs @@ -0,0 +1,51 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceProviderListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceProviderListResult.Serialization.cs new file mode 100644 index 0000000000..dd4d71e28e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceProviderListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceProviderListResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceProviderListResult.cs new file mode 100644 index 0000000000..1049d3073b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceProviderListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelector.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelector.Serialization.cs new file mode 100644 index 0000000000..6d5ec1b795 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelector.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelector.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelector.cs new file mode 100644 index 0000000000..e85c7541cb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelector.cs @@ -0,0 +1,72 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorExpression.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorExpression.Serialization.cs new file mode 100644 index 0000000000..4deb3a5e27 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorExpression.Serialization.cs @@ -0,0 +1,289 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorExpression.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorExpression.cs new file mode 100644 index 0000000000..c10dad80a6 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorExpression.cs @@ -0,0 +1,78 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorKind.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorKind.cs new file mode 100644 index 0000000000..bed65e9a77 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceSelectorKind.cs @@ -0,0 +1,57 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAlias.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAlias.Serialization.cs new file mode 100644 index 0000000000..74e70a3ebd --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAlias.Serialization.cs @@ -0,0 +1,350 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAlias.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAlias.cs new file mode 100644 index 0000000000..26ac43a913 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAlias.cs @@ -0,0 +1,92 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPath.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPath.Serialization.cs new file mode 100644 index 0000000000..f98d9c2e88 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPath.Serialization.cs @@ -0,0 +1,292 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPath.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPath.cs new file mode 100644 index 0000000000..acd74e09e7 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPath.cs @@ -0,0 +1,82 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathAttributes.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathAttributes.cs new file mode 100644 index 0000000000..217d95e60d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathAttributes.cs @@ -0,0 +1,51 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathMetadata.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathMetadata.Serialization.cs new file mode 100644 index 0000000000..6ba6a18823 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathMetadata.Serialization.cs @@ -0,0 +1,196 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathMetadata.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathMetadata.cs new file mode 100644 index 0000000000..1a4b48937b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathMetadata.cs @@ -0,0 +1,71 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathTokenType.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathTokenType.cs new file mode 100644 index 0000000000..98fd72b001 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPathTokenType.cs @@ -0,0 +1,69 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPattern.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPattern.Serialization.cs new file mode 100644 index 0000000000..1d5a9f69aa --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPattern.Serialization.cs @@ -0,0 +1,234 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPattern.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPattern.cs new file mode 100644 index 0000000000..5c318a2dde --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPattern.cs @@ -0,0 +1,76 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPatternType.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPatternType.Serialization.cs new file mode 100644 index 0000000000..8faaf01391 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPatternType.Serialization.cs @@ -0,0 +1,28 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPatternType.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPatternType.cs new file mode 100644 index 0000000000..8ed0430db1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasPatternType.cs @@ -0,0 +1,18 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasType.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasType.Serialization.cs new file mode 100644 index 0000000000..2ddd82d437 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasType.Serialization.cs @@ -0,0 +1,30 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasType.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasType.cs new file mode 100644 index 0000000000..b111828d70 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliasType.cs @@ -0,0 +1,20 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliases.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliases.Serialization.cs new file mode 100644 index 0000000000..a7ae258fb4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliases.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliases.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliases.cs new file mode 100644 index 0000000000..872c369df5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourceTypeAliases.cs @@ -0,0 +1,72 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesMoveContent.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesMoveContent.Serialization.cs new file mode 100644 index 0000000000..53ffc251c8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesMoveContent.Serialization.cs @@ -0,0 +1,158 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesMoveContent.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesMoveContent.cs new file mode 100644 index 0000000000..89139c1b2e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesMoveContent.cs @@ -0,0 +1,73 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesSku.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesSku.Serialization.cs new file mode 100644 index 0000000000..f3919ac07f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesSku.Serialization.cs @@ -0,0 +1,343 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesSku.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesSku.cs new file mode 100644 index 0000000000..1aa8907276 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ResourcesSku.cs @@ -0,0 +1,91 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/SpendingLimit.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/SpendingLimit.Serialization.cs new file mode 100644 index 0000000000..1330415ea3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/SpendingLimit.Serialization.cs @@ -0,0 +1,30 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/SpendingLimit.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/SpendingLimit.cs new file mode 100644 index 0000000000..f1cf361866 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/SpendingLimit.cs @@ -0,0 +1,20 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/SubResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/SubResource.cs new file mode 100644 index 0000000000..b5bc3d1195 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/SubResource.cs @@ -0,0 +1,58 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionListResult.Serialization.cs new file mode 100644 index 0000000000..5b5ebed45e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionListResult.Serialization.cs @@ -0,0 +1,216 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionListResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionListResult.cs new file mode 100644 index 0000000000..62586d3820 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionListResult.cs @@ -0,0 +1,80 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionPolicies.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionPolicies.Serialization.cs new file mode 100644 index 0000000000..66686ae62b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionPolicies.Serialization.cs @@ -0,0 +1,234 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionPolicies.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionPolicies.cs new file mode 100644 index 0000000000..e953221105 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionPolicies.cs @@ -0,0 +1,76 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionState.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionState.Serialization.cs new file mode 100644 index 0000000000..51a2212e62 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionState.Serialization.cs @@ -0,0 +1,34 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionState.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionState.cs new file mode 100644 index 0000000000..2c58d11912 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/SubscriptionState.cs @@ -0,0 +1,24 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/Tag.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/Tag.Serialization.cs new file mode 100644 index 0000000000..fb16f5f47d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/Tag.Serialization.cs @@ -0,0 +1,200 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/Tag.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/Tag.cs new file mode 100644 index 0000000000..694808ed76 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/Tag.cs @@ -0,0 +1,63 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/TagPatchMode.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TagPatchMode.cs new file mode 100644 index 0000000000..a9f204e236 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TagPatchMode.cs @@ -0,0 +1,54 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/TagResourcePatch.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TagResourcePatch.Serialization.cs new file mode 100644 index 0000000000..b9e2ceee21 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TagResourcePatch.Serialization.cs @@ -0,0 +1,148 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/TagResourcePatch.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TagResourcePatch.cs new file mode 100644 index 0000000000..dc4496a3c0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TagResourcePatch.cs @@ -0,0 +1,81 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/TenantCategory.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TenantCategory.Serialization.cs new file mode 100644 index 0000000000..a3d824a90a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TenantCategory.Serialization.cs @@ -0,0 +1,30 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/TenantCategory.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TenantCategory.cs new file mode 100644 index 0000000000..4de42a1b2f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TenantCategory.cs @@ -0,0 +1,20 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/TenantListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TenantListResult.Serialization.cs new file mode 100644 index 0000000000..a49ae121eb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TenantListResult.Serialization.cs @@ -0,0 +1,216 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/TenantListResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TenantListResult.cs new file mode 100644 index 0000000000..82c47daaf1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TenantListResult.cs @@ -0,0 +1,80 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProvider.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProvider.Serialization.cs new file mode 100644 index 0000000000..30a4ebe220 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProvider.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProvider.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProvider.cs new file mode 100644 index 0000000000..c32fa3cc1a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProvider.cs @@ -0,0 +1,72 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProviderListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProviderListResult.Serialization.cs new file mode 100644 index 0000000000..0230f94493 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProviderListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProviderListResult.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProviderListResult.cs new file mode 100644 index 0000000000..44043f0767 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TenantResourceProviderListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/TrackedResourceExtendedData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TrackedResourceExtendedData.Serialization.cs new file mode 100644 index 0000000000..dfdee13d11 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TrackedResourceExtendedData.Serialization.cs @@ -0,0 +1,313 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/TrackedResourceExtendedData.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TrackedResourceExtendedData.cs new file mode 100644 index 0000000000..1474b682eb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/TrackedResourceExtendedData.cs @@ -0,0 +1,80 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ZoneMapping.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ZoneMapping.Serialization.cs new file mode 100644 index 0000000000..b0d8d11192 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ZoneMapping.Serialization.cs @@ -0,0 +1,228 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/Models/ZoneMapping.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ZoneMapping.cs new file mode 100644 index 0000000000..78773bb967 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/Models/ZoneMapping.cs @@ -0,0 +1,73 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentCollection.cs new file mode 100644 index 0000000000..c424f0598d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentCollection.cs @@ -0,0 +1,630 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentData.Serialization.cs new file mode 100644 index 0000000000..9b5c12248b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentData.Serialization.cs @@ -0,0 +1,760 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentData.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentData.cs new file mode 100644 index 0000000000..f0a246cdc3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentData.cs @@ -0,0 +1,170 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentResource.Serialization.cs new file mode 100644 index 0000000000..407fb6014f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentResource.cs new file mode 100644 index 0000000000..be2bed645c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/PolicyAssignmentResource.cs @@ -0,0 +1,342 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/PolicyDefinitionData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/PolicyDefinitionData.Serialization.cs new file mode 100644 index 0000000000..9297c29849 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/PolicyDefinitionData.Serialization.cs @@ -0,0 +1,492 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/PolicyDefinitionData.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/PolicyDefinitionData.cs new file mode 100644 index 0000000000..6689f9af87 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/PolicyDefinitionData.cs @@ -0,0 +1,165 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/PolicySetDefinitionData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/PolicySetDefinitionData.Serialization.cs new file mode 100644 index 0000000000..54e1be4d49 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/PolicySetDefinitionData.Serialization.cs @@ -0,0 +1,517 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/PolicySetDefinitionData.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/PolicySetDefinitionData.cs new file mode 100644 index 0000000000..22dae46c74 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/PolicySetDefinitionData.cs @@ -0,0 +1,138 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ResourceGroupCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceGroupCollection.cs new file mode 100644 index 0000000000..6fa5910de7 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceGroupCollection.cs @@ -0,0 +1,500 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ResourceGroupData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceGroupData.Serialization.cs new file mode 100644 index 0000000000..0e82804dca --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceGroupData.Serialization.cs @@ -0,0 +1,352 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ResourceGroupData.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceGroupData.cs new file mode 100644 index 0000000000..86a684655c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceGroupData.cs @@ -0,0 +1,95 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ResourceGroupResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceGroupResource.Serialization.cs new file mode 100644 index 0000000000..65a084b9bc --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceGroupResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ResourceGroupResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceGroupResource.cs new file mode 100644 index 0000000000..049966950d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceGroupResource.cs @@ -0,0 +1,980 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ResourceManagerModelFactory.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceManagerModelFactory.cs new file mode 100644 index 0000000000..c17962de61 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceManagerModelFactory.cs @@ -0,0 +1,764 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ResourceProviderCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceProviderCollection.cs new file mode 100644 index 0000000000..5915ae4051 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceProviderCollection.cs @@ -0,0 +1,389 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ResourceProviderData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceProviderData.Serialization.cs new file mode 100644 index 0000000000..98cd1f22ff --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceProviderData.Serialization.cs @@ -0,0 +1,355 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ResourceProviderData.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceProviderData.cs new file mode 100644 index 0000000000..e18d3655a2 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceProviderData.cs @@ -0,0 +1,87 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ResourceProviderResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceProviderResource.Serialization.cs new file mode 100644 index 0000000000..cff873e5de --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceProviderResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/ResourceProviderResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceProviderResource.cs new file mode 100644 index 0000000000..1644e4e793 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/ResourceProviderResource.cs @@ -0,0 +1,509 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/RestOperations/DataPolicyManifestsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/DataPolicyManifestsRestOperations.cs new file mode 100644 index 0000000000..b94f641cd7 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/DataPolicyManifestsRestOperations.cs @@ -0,0 +1,265 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/RestOperations/FeaturesRestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/FeaturesRestOperations.cs new file mode 100644 index 0000000000..6eda9037c4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/FeaturesRestOperations.cs @@ -0,0 +1,643 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/RestOperations/ManagementLocksRestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/ManagementLocksRestOperations.cs new file mode 100644 index 0000000000..66b3dc6664 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/ManagementLocksRestOperations.cs @@ -0,0 +1,459 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicyAssignmentsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicyAssignmentsRestOperations.cs new file mode 100644 index 0000000000..8437bfbc9f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicyAssignmentsRestOperations.cs @@ -0,0 +1,1183 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicyDefinitionsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicyDefinitionsRestOperations.cs new file mode 100644 index 0000000000..d8a8f6ee24 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicyDefinitionsRestOperations.cs @@ -0,0 +1,1145 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicySetDefinitionsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicySetDefinitionsRestOperations.cs new file mode 100644 index 0000000000..74741a5519 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/PolicySetDefinitionsRestOperations.cs @@ -0,0 +1,1149 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/RestOperations/ProviderResourceTypesRestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/ProviderResourceTypesRestOperations.cs new file mode 100644 index 0000000000..3acae9da9e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/ProviderResourceTypesRestOperations.cs @@ -0,0 +1,135 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/RestOperations/ProvidersRestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/ProvidersRestOperations.cs new file mode 100644 index 0000000000..63f444d6e3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/ProvidersRestOperations.cs @@ -0,0 +1,802 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourceGroupsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourceGroupsRestOperations.cs new file mode 100644 index 0000000000..06b9758562 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourceGroupsRestOperations.cs @@ -0,0 +1,663 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourceManagementRestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourceManagementRestOperations.cs new file mode 100644 index 0000000000..490f691f55 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourceManagementRestOperations.cs @@ -0,0 +1,112 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourcesRestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourcesRestOperations.cs new file mode 100644 index 0000000000..c990c23b40 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/ResourcesRestOperations.cs @@ -0,0 +1,915 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/RestOperations/SubscriptionsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/SubscriptionsRestOperations.cs new file mode 100644 index 0000000000..a5f94cca14 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/SubscriptionsRestOperations.cs @@ -0,0 +1,341 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/RestOperations/TagsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/TagsRestOperations.cs new file mode 100644 index 0000000000..ac7c58fb5a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/TagsRestOperations.cs @@ -0,0 +1,833 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/RestOperations/TenantsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/TenantsRestOperations.cs new file mode 100644 index 0000000000..25264b970e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/RestOperations/TenantsRestOperations.cs @@ -0,0 +1,182 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/SubscriptionCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionCollection.cs new file mode 100644 index 0000000000..8ff124397b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionCollection.cs @@ -0,0 +1,394 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/SubscriptionData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionData.Serialization.cs new file mode 100644 index 0000000000..8574e5e3ba --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionData.Serialization.cs @@ -0,0 +1,481 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/SubscriptionData.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionData.cs new file mode 100644 index 0000000000..02537ef7b6 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionData.cs @@ -0,0 +1,109 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionCollection.cs new file mode 100644 index 0000000000..e0e348db73 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionCollection.cs @@ -0,0 +1,500 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionResource.Serialization.cs new file mode 100644 index 0000000000..d98f9066c1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionResource.cs new file mode 100644 index 0000000000..415bda5437 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicyDefinitionResource.cs @@ -0,0 +1,353 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionCollection.cs new file mode 100644 index 0000000000..3f7c59a96f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionCollection.cs @@ -0,0 +1,500 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionResource.Serialization.cs new file mode 100644 index 0000000000..2c9efcff84 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionResource.cs new file mode 100644 index 0000000000..9bf306c256 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionPolicySetDefinitionResource.cs @@ -0,0 +1,353 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/SubscriptionResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionResource.Serialization.cs new file mode 100644 index 0000000000..138601640e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/SubscriptionResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionResource.cs new file mode 100644 index 0000000000..e484fd200a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/SubscriptionResource.cs @@ -0,0 +1,962 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/TagResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TagResource.Serialization.cs new file mode 100644 index 0000000000..14b43eb7c4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TagResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/TagResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TagResource.cs new file mode 100644 index 0000000000..f63e4775de --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TagResource.cs @@ -0,0 +1,437 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/TagResourceData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TagResourceData.Serialization.cs new file mode 100644 index 0000000000..20fac26bfb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TagResourceData.Serialization.cs @@ -0,0 +1,237 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/TagResourceData.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TagResourceData.cs new file mode 100644 index 0000000000..8bda3dfa58 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TagResourceData.cs @@ -0,0 +1,96 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/TenantCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantCollection.cs new file mode 100644 index 0000000000..53cd523d8b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantCollection.cs @@ -0,0 +1,199 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/TenantData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantData.Serialization.cs new file mode 100644 index 0000000000..46a0ba5c76 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantData.Serialization.cs @@ -0,0 +1,504 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/TenantData.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantData.cs new file mode 100644 index 0000000000..7d91999217 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantData.cs @@ -0,0 +1,116 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionCollection.cs new file mode 100644 index 0000000000..bd817fab6a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionCollection.cs @@ -0,0 +1,398 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionResource.Serialization.cs new file mode 100644 index 0000000000..6d08620cc8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionResource.cs new file mode 100644 index 0000000000..a8464ce670 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantPolicyDefinitionResource.cs @@ -0,0 +1,168 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionCollection.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionCollection.cs new file mode 100644 index 0000000000..dbc7feb42d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionCollection.cs @@ -0,0 +1,398 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionResource.Serialization.cs new file mode 100644 index 0000000000..e2e25a534c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionResource.cs new file mode 100644 index 0000000000..ca45c6dc6a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantPolicySetDefinitionResource.cs @@ -0,0 +1,168 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/TenantResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantResource.Serialization.cs new file mode 100644 index 0000000000..7b9b360a83 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/after/Resources/Generated/TenantResource.cs b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantResource.cs new file mode 100644 index 0000000000..1b1536a286 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Resources/Generated/TenantResource.cs @@ -0,0 +1,505 @@ +// 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/dotnet-aot-compat/after/Shared/AppContextSwitchHelper.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/AppContextSwitchHelper.cs new file mode 100644 index 0000000000..6b511aae6c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/AppContextSwitchHelper.cs @@ -0,0 +1,42 @@ +// 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/dotnet-aot-compat/after/Shared/AsyncLockWithValue.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/AsyncLockWithValue.cs new file mode 100644 index 0000000000..96aa1a559c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/AsyncLockWithValue.cs @@ -0,0 +1,260 @@ +// 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/dotnet-aot-compat/after/Shared/AzureResourceProviderNamespaceAttribute.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/AzureResourceProviderNamespaceAttribute.cs new file mode 100644 index 0000000000..e9ac665a94 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/AzureResourceProviderNamespaceAttribute.cs @@ -0,0 +1,22 @@ +// 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/dotnet-aot-compat/after/Shared/ClientDiagnostics.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/ClientDiagnostics.cs new file mode 100644 index 0000000000..f9fc345937 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/ClientDiagnostics.cs @@ -0,0 +1,73 @@ +// 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/dotnet-aot-compat/after/Shared/DiagnosticScope.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/DiagnosticScope.cs new file mode 100644 index 0000000000..c32bf2b8cb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/DiagnosticScope.cs @@ -0,0 +1,448 @@ +// 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/dotnet-aot-compat/after/Shared/DiagnosticScopeFactory.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/DiagnosticScopeFactory.cs new file mode 100644 index 0000000000..5e1d9c556e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/DiagnosticScopeFactory.cs @@ -0,0 +1,103 @@ +// 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/dotnet-aot-compat/after/Shared/FixedDelayWithNoJitterStrategy.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/FixedDelayWithNoJitterStrategy.cs new file mode 100644 index 0000000000..1051e56b3f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/FixedDelayWithNoJitterStrategy.cs @@ -0,0 +1,26 @@ +// 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/dotnet-aot-compat/after/Shared/ForwardsClientCallsAttribute.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/ForwardsClientCallsAttribute.cs new file mode 100644 index 0000000000..e9e933541b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/ForwardsClientCallsAttribute.cs @@ -0,0 +1,39 @@ +// 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/dotnet-aot-compat/after/Shared/HashCodeBuilder.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/HashCodeBuilder.cs new file mode 100644 index 0000000000..a6a76f93f8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/HashCodeBuilder.cs @@ -0,0 +1,387 @@ +// 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/dotnet-aot-compat/after/Shared/HttpMessageSanitizer.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/HttpMessageSanitizer.cs new file mode 100644 index 0000000000..36becf22a5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/HttpMessageSanitizer.cs @@ -0,0 +1,198 @@ +// 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/dotnet-aot-compat/after/Shared/HttpPipelineExtensions.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/HttpPipelineExtensions.cs new file mode 100644 index 0000000000..231f13cf53 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/HttpPipelineExtensions.cs @@ -0,0 +1,110 @@ +// 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/dotnet-aot-compat/after/Shared/IOperationSource.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/IOperationSource.cs new file mode 100644 index 0000000000..1be2f9b733 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/IOperationSource.cs @@ -0,0 +1,14 @@ +// 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/dotnet-aot-compat/after/Shared/IUtf8JsonSerializable.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/IUtf8JsonSerializable.cs new file mode 100644 index 0000000000..5653e46093 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/IUtf8JsonSerializable.cs @@ -0,0 +1,14 @@ +// 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/dotnet-aot-compat/after/Shared/InitializationConstructorAttribute.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/InitializationConstructorAttribute.cs new file mode 100644 index 0000000000..d087b58c2a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/InitializationConstructorAttribute.cs @@ -0,0 +1,15 @@ +// 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/dotnet-aot-compat/after/Shared/ManagedServiceIdentityTypeV3Converter.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/ManagedServiceIdentityTypeV3Converter.cs new file mode 100644 index 0000000000..b33c186e19 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/ManagedServiceIdentityTypeV3Converter.cs @@ -0,0 +1,53 @@ +// 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/dotnet-aot-compat/after/Shared/NextLinkOperationImplementation.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/NextLinkOperationImplementation.cs new file mode 100644 index 0000000000..d4dc0403e2 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/NextLinkOperationImplementation.cs @@ -0,0 +1,701 @@ +// 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/dotnet-aot-compat/after/Shared/NoValueResponseOfT.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/NoValueResponseOfT.cs new file mode 100644 index 0000000000..95fa1e2573 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/NoValueResponseOfT.cs @@ -0,0 +1,39 @@ +// 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/dotnet-aot-compat/after/Shared/OperationFinalStateVia.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/OperationFinalStateVia.cs new file mode 100644 index 0000000000..8ad2396db9 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/OperationFinalStateVia.cs @@ -0,0 +1,16 @@ +// 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/dotnet-aot-compat/after/Shared/OperationInternal.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/OperationInternal.cs new file mode 100644 index 0000000000..2435465459 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/OperationInternal.cs @@ -0,0 +1,263 @@ +// 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/dotnet-aot-compat/after/Shared/OperationInternalBase.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/OperationInternalBase.cs new file mode 100644 index 0000000000..dad6480c22 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/OperationInternalBase.cs @@ -0,0 +1,234 @@ +// 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/dotnet-aot-compat/after/Shared/OperationInternalOfT.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/OperationInternalOfT.cs new file mode 100644 index 0000000000..c1adc58603 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/OperationInternalOfT.cs @@ -0,0 +1,431 @@ +// 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/dotnet-aot-compat/after/Shared/OperationPoller.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/OperationPoller.cs new file mode 100644 index 0000000000..4cbd975ebb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/OperationPoller.cs @@ -0,0 +1,114 @@ +// 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/dotnet-aot-compat/after/Shared/Page.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/Page.cs new file mode 100644 index 0000000000..1438fdfd5f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/Page.cs @@ -0,0 +1,16 @@ +// 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/dotnet-aot-compat/after/Shared/PageableHelpers.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/PageableHelpers.cs new file mode 100644 index 0000000000..4d15951fef --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/PageableHelpers.cs @@ -0,0 +1,556 @@ +// 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/dotnet-aot-compat/after/Shared/PropertyReferenceTypeAttribute.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/PropertyReferenceTypeAttribute.cs new file mode 100644 index 0000000000..141b350a5e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/PropertyReferenceTypeAttribute.cs @@ -0,0 +1,52 @@ +// 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/dotnet-aot-compat/after/Shared/ProtocolOperation.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/ProtocolOperation.cs new file mode 100644 index 0000000000..ce76a07848 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/ProtocolOperation.cs @@ -0,0 +1,78 @@ +// 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/dotnet-aot-compat/after/Shared/RawRequestUriBuilder.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/RawRequestUriBuilder.cs new file mode 100644 index 0000000000..f48b1f6ed6 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/RawRequestUriBuilder.cs @@ -0,0 +1,229 @@ +// 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/dotnet-aot-compat/after/Shared/ReferenceTypeAttribute.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/ReferenceTypeAttribute.cs new file mode 100644 index 0000000000..04e86cc394 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/ReferenceTypeAttribute.cs @@ -0,0 +1,36 @@ +// 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/dotnet-aot-compat/after/Shared/ResponseErrorConverter.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/ResponseErrorConverter.cs new file mode 100644 index 0000000000..60de2e908d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/ResponseErrorConverter.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/after/Shared/SequentialDelayStrategy.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/SequentialDelayStrategy.cs new file mode 100644 index 0000000000..5185fa1201 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/SequentialDelayStrategy.cs @@ -0,0 +1,38 @@ +// 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/dotnet-aot-compat/after/Shared/SerializationConstructorAttribute.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/SerializationConstructorAttribute.cs new file mode 100644 index 0000000000..fbe9465541 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/SerializationConstructorAttribute.cs @@ -0,0 +1,15 @@ +// 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/dotnet-aot-compat/after/Shared/SharedExtensions.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/SharedExtensions.cs new file mode 100644 index 0000000000..215fd316e5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/SharedExtensions.cs @@ -0,0 +1,82 @@ +// 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/dotnet-aot-compat/after/Shared/TaskExtensions.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/TaskExtensions.cs new file mode 100644 index 0000000000..9748653782 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/TaskExtensions.cs @@ -0,0 +1,313 @@ +// 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/dotnet-aot-compat/after/Shared/TypeFormatters.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/TypeFormatters.cs new file mode 100644 index 0000000000..6bb51d611c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/TypeFormatters.cs @@ -0,0 +1,159 @@ +// 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/dotnet-aot-compat/after/Shared/TypeReferenceTypeAttribute.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/TypeReferenceTypeAttribute.cs new file mode 100644 index 0000000000..dce5c4f331 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/TypeReferenceTypeAttribute.cs @@ -0,0 +1,41 @@ +// 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/dotnet-aot-compat/after/Shared/VoidValue.cs b/tests/dotnet/dotnet-aot-compat/after/Shared/VoidValue.cs new file mode 100644 index 0000000000..cb52e0eafb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/Shared/VoidValue.cs @@ -0,0 +1,10 @@ +// 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/dotnet-aot-compat/after/autorest.md b/tests/dotnet/dotnet-aot-compat/after/autorest.md new file mode 100644 index 0000000000..3735f0952b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/autorest.md @@ -0,0 +1,839 @@ +# 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/dotnet-aot-compat/after/global.json b/tests/dotnet/dotnet-aot-compat/after/global.json new file mode 100644 index 0000000000..3be1c15acd --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/after/global.json @@ -0,0 +1,6 @@ +{ + "sdk": { + "version": "9.0.300", + "rollForward": "latestFeature" + } +} diff --git a/tests/dotnet/dotnet-aot-compat/before/.gitignore b/tests/dotnet/dotnet-aot-compat/before/.gitignore new file mode 100644 index 0000000000..cd42ee34e8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/.gitignore @@ -0,0 +1,2 @@ +bin/ +obj/ diff --git a/tests/dotnet/dotnet-aot-compat/before/ArmClient.cs b/tests/dotnet/dotnet-aot-compat/before/ArmClient.cs new file mode 100644 index 0000000000..2993823501 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ArmClient.cs @@ -0,0 +1,315 @@ +// 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/dotnet-aot-compat/before/ArmClientOptions.cs b/tests/dotnet/dotnet-aot-compat/before/ArmClientOptions.cs new file mode 100644 index 0000000000..dc9d5b6cc6 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ArmClientOptions.cs @@ -0,0 +1,81 @@ +// 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/dotnet-aot-compat/before/ArmCollection.cs b/tests/dotnet/dotnet-aot-compat/before/ArmCollection.cs new file mode 100644 index 0000000000..c3b5b1b084 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ArmCollection.cs @@ -0,0 +1,84 @@ +// 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/dotnet-aot-compat/before/ArmEnvironment.cs b/tests/dotnet/dotnet-aot-compat/before/ArmEnvironment.cs new file mode 100644 index 0000000000..cc8fe784fb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ArmEnvironment.cs @@ -0,0 +1,82 @@ +// 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/dotnet-aot-compat/before/ArmOperation.cs b/tests/dotnet/dotnet-aot-compat/before/ArmOperation.cs new file mode 100644 index 0000000000..363ed99fff --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ArmOperation.cs @@ -0,0 +1,113 @@ +// 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/dotnet-aot-compat/before/ArmOperationOfT.cs b/tests/dotnet/dotnet-aot-compat/before/ArmOperationOfT.cs new file mode 100644 index 0000000000..5b23a5d6a7 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ArmOperationOfT.cs @@ -0,0 +1,15 @@ +// 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/dotnet-aot-compat/before/ArmResource.cs b/tests/dotnet/dotnet-aot-compat/before/ArmResource.cs new file mode 100644 index 0000000000..3e5e82e19b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ArmResource.cs @@ -0,0 +1,140 @@ +// 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/dotnet-aot-compat/before/Assets/Profile/2020-09-01-hybrid.json b/tests/dotnet/dotnet-aot-compat/before/Assets/Profile/2020-09-01-hybrid.json new file mode 100644 index 0000000000..d19b2f0667 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Assets/Profile/2020-09-01-hybrid.json @@ -0,0 +1,678 @@ +{ + "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/dotnet-aot-compat/before/Azure.ResourceManager.csproj b/tests/dotnet/dotnet-aot-compat/before/Azure.ResourceManager.csproj new file mode 100644 index 0000000000..eed99d9d6d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Azure.ResourceManager.csproj @@ -0,0 +1,30 @@ + + + + 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/dotnet-aot-compat/before/AzureStackProfile.cs b/tests/dotnet/dotnet-aot-compat/before/AzureStackProfile.cs new file mode 100644 index 0000000000..09f285c061 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/AzureStackProfile.cs @@ -0,0 +1,14 @@ +// 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/dotnet-aot-compat/before/BicepModelReaderWriterOptions.cs b/tests/dotnet/dotnet-aot-compat/before/BicepModelReaderWriterOptions.cs new file mode 100644 index 0000000000..eaa886e500 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/BicepModelReaderWriterOptions.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/before/CodeGenAttributes.cs b/tests/dotnet/dotnet-aot-compat/before/CodeGenAttributes.cs new file mode 100644 index 0000000000..efc951c129 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/CodeGenAttributes.cs @@ -0,0 +1,65 @@ +// 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/dotnet-aot-compat/before/Common/Custom/Models/ArmPlan.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/ArmPlan.cs new file mode 100644 index 0000000000..35564305f8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/ArmPlan.cs @@ -0,0 +1,95 @@ +// 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/dotnet-aot-compat/before/Common/Custom/Models/ArmSku.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/ArmSku.cs new file mode 100644 index 0000000000..ce20416eb1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/ArmSku.cs @@ -0,0 +1,95 @@ +// 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/dotnet-aot-compat/before/Common/Custom/Models/EncryptionProperties.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/EncryptionProperties.cs new file mode 100644 index 0000000000..a5a35be565 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/EncryptionProperties.cs @@ -0,0 +1,18 @@ +// 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/dotnet-aot-compat/before/Common/Custom/Models/EncryptionStatus.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/EncryptionStatus.cs new file mode 100644 index 0000000000..c1fc8e2bbc --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/EncryptionStatus.cs @@ -0,0 +1,18 @@ +// 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/dotnet-aot-compat/before/Common/Custom/Models/KeyVaultProperties.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/KeyVaultProperties.cs new file mode 100644 index 0000000000..5b49b0341a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/KeyVaultProperties.cs @@ -0,0 +1,18 @@ +// 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/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentity.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentity.Serialization.cs new file mode 100644 index 0000000000..470061ab7d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentity.Serialization.cs @@ -0,0 +1,263 @@ +// 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/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentity.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentity.cs new file mode 100644 index 0000000000..96313186cf --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentity.cs @@ -0,0 +1,48 @@ +// 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/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentityType.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentityType.cs new file mode 100644 index 0000000000..7954ef73df --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/ManagedServiceIdentityType.cs @@ -0,0 +1,37 @@ +// 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/dotnet-aot-compat/before/Common/Custom/Models/SystemAssignedServiceIdentity.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/SystemAssignedServiceIdentity.cs new file mode 100644 index 0000000000..e887668292 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/SystemAssignedServiceIdentity.cs @@ -0,0 +1,65 @@ +// 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/dotnet-aot-compat/before/Common/Custom/Models/SystemAssignedServiceIdentityType.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/SystemAssignedServiceIdentityType.cs new file mode 100644 index 0000000000..15fb71110a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/Models/SystemAssignedServiceIdentityType.cs @@ -0,0 +1,17 @@ +// 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/dotnet-aot-compat/before/Common/Custom/ResourceManagerModelFactory.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/ResourceManagerModelFactory.cs new file mode 100644 index 0000000000..c5d2b26469 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Custom/ResourceManagerModelFactory.cs @@ -0,0 +1,25 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Internal/Argument.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Internal/Argument.cs new file mode 100644 index 0000000000..0e6dfdb59a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Internal/Argument.cs @@ -0,0 +1,129 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Internal/BicepSerializationHelpers.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Internal/BicepSerializationHelpers.cs new file mode 100644 index 0000000000..633bf5b166 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Internal/BicepSerializationHelpers.cs @@ -0,0 +1,58 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Internal/ChangeTrackingDictionary.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Internal/ChangeTrackingDictionary.cs new file mode 100644 index 0000000000..3e0457dd83 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Internal/ChangeTrackingDictionary.cs @@ -0,0 +1,167 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Internal/ChangeTrackingList.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Internal/ChangeTrackingList.cs new file mode 100644 index 0000000000..1837046c52 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Internal/ChangeTrackingList.cs @@ -0,0 +1,153 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Internal/ModelSerializationExtensions.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Internal/ModelSerializationExtensions.cs new file mode 100644 index 0000000000..c879f184e7 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Internal/ModelSerializationExtensions.cs @@ -0,0 +1,407 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Internal/Optional.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Internal/Optional.cs new file mode 100644 index 0000000000..c21cb37eee --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Internal/Optional.cs @@ -0,0 +1,51 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Internal/WirePathAttribute.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Internal/WirePathAttribute.cs new file mode 100644 index 0000000000..6a974d2a89 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Internal/WirePathAttribute.cs @@ -0,0 +1,27 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/ArmPlan.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/ArmPlan.Serialization.cs new file mode 100644 index 0000000000..95e2fd6d05 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/ArmPlan.Serialization.cs @@ -0,0 +1,291 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/ArmPlan.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/ArmPlan.cs new file mode 100644 index 0000000000..711ac5f348 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/ArmPlan.cs @@ -0,0 +1,71 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/ArmSku.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/ArmSku.Serialization.cs new file mode 100644 index 0000000000..ee12d1ffab --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/ArmSku.Serialization.cs @@ -0,0 +1,289 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/ArmSku.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/ArmSku.cs new file mode 100644 index 0000000000..4a4de3ba03 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/ArmSku.cs @@ -0,0 +1,65 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/ArmSkuTier.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/ArmSkuTier.Serialization.cs new file mode 100644 index 0000000000..c640e16a48 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/ArmSkuTier.Serialization.cs @@ -0,0 +1,32 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/ArmSkuTier.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/ArmSkuTier.cs new file mode 100644 index 0000000000..4320a2d3b4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/ArmSkuTier.cs @@ -0,0 +1,22 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/AzureResourceManagerContext.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/AzureResourceManagerContext.cs new file mode 100644 index 0000000000..f26fee2f3a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/AzureResourceManagerContext.cs @@ -0,0 +1,19 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/CreatedByType.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/CreatedByType.cs new file mode 100644 index 0000000000..f7a4c34f58 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/CreatedByType.cs @@ -0,0 +1,57 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/EncryptionProperties.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/EncryptionProperties.Serialization.cs new file mode 100644 index 0000000000..bc9ff0979a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/EncryptionProperties.Serialization.cs @@ -0,0 +1,190 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/EncryptionProperties.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/EncryptionProperties.cs new file mode 100644 index 0000000000..5b441bcc81 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/EncryptionProperties.cs @@ -0,0 +1,39 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/EncryptionStatus.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/EncryptionStatus.cs new file mode 100644 index 0000000000..c69242b97c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/EncryptionStatus.cs @@ -0,0 +1,51 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/KeyVaultProperties.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/KeyVaultProperties.Serialization.cs new file mode 100644 index 0000000000..5280cd7b90 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/KeyVaultProperties.Serialization.cs @@ -0,0 +1,198 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/KeyVaultProperties.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/KeyVaultProperties.cs new file mode 100644 index 0000000000..2e92a30cff --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/KeyVaultProperties.cs @@ -0,0 +1,39 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/ManagedServiceIdentityType.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/ManagedServiceIdentityType.cs new file mode 100644 index 0000000000..826953ce1c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/ManagedServiceIdentityType.cs @@ -0,0 +1,57 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/OperationStatusResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/OperationStatusResult.Serialization.cs new file mode 100644 index 0000000000..b28ac42cb6 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/OperationStatusResult.Serialization.cs @@ -0,0 +1,407 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/OperationStatusResult.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/OperationStatusResult.cs new file mode 100644 index 0000000000..5a902c73e8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/OperationStatusResult.cs @@ -0,0 +1,79 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/ResourceData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/ResourceData.Serialization.cs new file mode 100644 index 0000000000..1b659410bc --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/ResourceData.Serialization.cs @@ -0,0 +1,41 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/ResourceData.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/ResourceData.cs new file mode 100644 index 0000000000..841b931f44 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/ResourceData.cs @@ -0,0 +1,45 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentity.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentity.Serialization.cs new file mode 100644 index 0000000000..2e420c90b8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentity.Serialization.cs @@ -0,0 +1,210 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentity.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentity.cs new file mode 100644 index 0000000000..f7feea87c2 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentity.cs @@ -0,0 +1,22 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentityType.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentityType.cs new file mode 100644 index 0000000000..ab44e79a42 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/SystemAssignedServiceIdentityType.cs @@ -0,0 +1,51 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/SystemData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/SystemData.Serialization.cs new file mode 100644 index 0000000000..513fa91320 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/SystemData.Serialization.cs @@ -0,0 +1,326 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/SystemData.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/SystemData.cs new file mode 100644 index 0000000000..14d762f3b5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/SystemData.cs @@ -0,0 +1,60 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/TrackedResourceData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/TrackedResourceData.Serialization.cs new file mode 100644 index 0000000000..a6af3ca008 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/TrackedResourceData.Serialization.cs @@ -0,0 +1,35 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/TrackedResourceData.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/TrackedResourceData.cs new file mode 100644 index 0000000000..741469301d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/TrackedResourceData.cs @@ -0,0 +1,50 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/UserAssignedIdentity.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/UserAssignedIdentity.Serialization.cs new file mode 100644 index 0000000000..ad78fdb6bc --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/UserAssignedIdentity.Serialization.cs @@ -0,0 +1,190 @@ +// 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/dotnet-aot-compat/before/Common/Generated/Models/UserAssignedIdentity.cs b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/UserAssignedIdentity.cs new file mode 100644 index 0000000000..727197fddd --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Common/Generated/Models/UserAssignedIdentity.cs @@ -0,0 +1,40 @@ +// 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/dotnet-aot-compat/before/Directory.Build.props b/tests/dotnet/dotnet-aot-compat/before/Directory.Build.props new file mode 100644 index 0000000000..8c119d5413 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Directory.Build.props @@ -0,0 +1,2 @@ + + diff --git a/tests/dotnet/dotnet-aot-compat/before/Directory.Packages.props b/tests/dotnet/dotnet-aot-compat/before/Directory.Packages.props new file mode 100644 index 0000000000..5fc7d2a08a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Directory.Packages.props @@ -0,0 +1,10 @@ + + + true + + + + + + + diff --git a/tests/dotnet/dotnet-aot-compat/before/ExperimentalAttribute.cs b/tests/dotnet/dotnet-aot-compat/before/ExperimentalAttribute.cs new file mode 100644 index 0000000000..9465ac0f52 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ExperimentalAttribute.cs @@ -0,0 +1,60 @@ +// 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/dotnet-aot-compat/before/Extensions/ArmClientBuilderExtensions.cs b/tests/dotnet/dotnet-aot-compat/before/Extensions/ArmClientBuilderExtensions.cs new file mode 100644 index 0000000000..6b08a9df52 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Extensions/ArmClientBuilderExtensions.cs @@ -0,0 +1,33 @@ +// 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/dotnet-aot-compat/before/GenericOperationSource.cs b/tests/dotnet/dotnet-aot-compat/before/GenericOperationSource.cs new file mode 100644 index 0000000000..cb5c47a9f5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/GenericOperationSource.cs @@ -0,0 +1,44 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Custom/HelperSuppressions.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Custom/HelperSuppressions.cs new file mode 100644 index 0000000000..dfe77b4da6 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Custom/HelperSuppressions.cs @@ -0,0 +1,13 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Custom/ManagementGroupResource.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Custom/ManagementGroupResource.cs new file mode 100644 index 0000000000..809c4fff69 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Custom/ManagementGroupResource.cs @@ -0,0 +1,26 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Custom/Models/ManagementGroupNameAvailabilityContent.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Custom/Models/ManagementGroupNameAvailabilityContent.cs new file mode 100644 index 0000000000..a033177eb0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Custom/Models/ManagementGroupNameAvailabilityContent.cs @@ -0,0 +1,18 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Extensions/ArmClient.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Extensions/ArmClient.cs new file mode 100644 index 0000000000..6881f263fc --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Extensions/ArmClient.cs @@ -0,0 +1,39 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Extensions/TenantResource.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Extensions/TenantResource.cs new file mode 100644 index 0000000000..457e521a66 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Extensions/TenantResource.cs @@ -0,0 +1,98 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Internal/WirePathAttribute.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Internal/WirePathAttribute.cs new file mode 100644 index 0000000000..9f3fd65374 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Internal/WirePathAttribute.cs @@ -0,0 +1,27 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupOperationSource.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupOperationSource.cs new file mode 100644 index 0000000000..b7ed659f6a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupOperationSource.cs @@ -0,0 +1,36 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperation.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperation.cs new file mode 100644 index 0000000000..5e967bcda8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperation.cs @@ -0,0 +1,94 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperationOfT.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperationOfT.cs new file mode 100644 index 0000000000..aa441fcede --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/LongRunningOperation/ManagementGroupsArmOperationOfT.cs @@ -0,0 +1,100 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupCollection.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupCollection.cs new file mode 100644 index 0000000000..888276d7e4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupCollection.cs @@ -0,0 +1,688 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupData.Serialization.cs new file mode 100644 index 0000000000..28569c1e7b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupData.Serialization.cs @@ -0,0 +1,383 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupData.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupData.cs new file mode 100644 index 0000000000..5b5b364b1d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupData.cs @@ -0,0 +1,92 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupResource.Serialization.cs new file mode 100644 index 0000000000..daf7ad8478 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupResource.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupResource.cs new file mode 100644 index 0000000000..596e9a0bbf --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupResource.cs @@ -0,0 +1,505 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionCollection.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionCollection.cs new file mode 100644 index 0000000000..9f8a56d321 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionCollection.cs @@ -0,0 +1,516 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionData.Serialization.cs new file mode 100644 index 0000000000..f616dc610d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionData.Serialization.cs @@ -0,0 +1,377 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionData.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionData.cs new file mode 100644 index 0000000000..012a80ff0c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionData.cs @@ -0,0 +1,97 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionResource.Serialization.cs new file mode 100644 index 0000000000..27395325f3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionResource.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionResource.cs new file mode 100644 index 0000000000..084663c338 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ManagementGroupSubscriptionResource.cs @@ -0,0 +1,357 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/CreateManagementGroupDetails.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/CreateManagementGroupDetails.Serialization.cs new file mode 100644 index 0000000000..167dd7d592 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/CreateManagementGroupDetails.Serialization.cs @@ -0,0 +1,174 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/CreateManagementGroupDetails.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/CreateManagementGroupDetails.cs new file mode 100644 index 0000000000..6cfb0e466c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/CreateManagementGroupDetails.cs @@ -0,0 +1,81 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantData.Serialization.cs new file mode 100644 index 0000000000..e9b4dc430a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantData.Serialization.cs @@ -0,0 +1,318 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantData.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantData.cs new file mode 100644 index 0000000000..b6d4f43ca7 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantData.cs @@ -0,0 +1,82 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantListResult.Serialization.cs new file mode 100644 index 0000000000..6cbae7deda --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantListResult.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantListResult.cs new file mode 100644 index 0000000000..df6d43351c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantParentGroupInfo.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantParentGroupInfo.Serialization.cs new file mode 100644 index 0000000000..86394650aa --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantParentGroupInfo.Serialization.cs @@ -0,0 +1,166 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantParentGroupInfo.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantParentGroupInfo.cs new file mode 100644 index 0000000000..5dd49bf750 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/DescendantParentGroupInfo.cs @@ -0,0 +1,67 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityData.Serialization.cs new file mode 100644 index 0000000000..6485645aad --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityData.Serialization.cs @@ -0,0 +1,686 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityData.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityData.cs new file mode 100644 index 0000000000..08b09466be --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityData.cs @@ -0,0 +1,126 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityListResult.Serialization.cs new file mode 100644 index 0000000000..b91683219a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityListResult.Serialization.cs @@ -0,0 +1,249 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityListResult.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityListResult.cs new file mode 100644 index 0000000000..64d4927aa3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityListResult.cs @@ -0,0 +1,74 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityPermission.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityPermission.Serialization.cs new file mode 100644 index 0000000000..a83caa1d91 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityPermission.Serialization.cs @@ -0,0 +1,32 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityPermission.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityPermission.cs new file mode 100644 index 0000000000..c7a2a6c4cb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityPermission.cs @@ -0,0 +1,22 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntitySearchOption.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntitySearchOption.cs new file mode 100644 index 0000000000..f4893f29e1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntitySearchOption.cs @@ -0,0 +1,60 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityViewOption.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityViewOption.cs new file mode 100644 index 0000000000..d9b563079f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/EntityViewOption.cs @@ -0,0 +1,57 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.Serialization.cs new file mode 100644 index 0000000000..d11c5c97e0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.cs new file mode 100644 index 0000000000..2b3b56a128 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ListSubscriptionUnderManagementGroup.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildInfo.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildInfo.Serialization.cs new file mode 100644 index 0000000000..bf90302465 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildInfo.Serialization.cs @@ -0,0 +1,308 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildInfo.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildInfo.cs new file mode 100644 index 0000000000..57e19925e0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildInfo.cs @@ -0,0 +1,87 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildOptions.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildOptions.Serialization.cs new file mode 100644 index 0000000000..c9d1017ba4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildOptions.Serialization.cs @@ -0,0 +1,197 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildOptions.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildOptions.cs new file mode 100644 index 0000000000..fa5796a8fe --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildOptions.cs @@ -0,0 +1,87 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildType.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildType.cs new file mode 100644 index 0000000000..75e6a37c4a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupChildType.cs @@ -0,0 +1,51 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCollectionGetEntitiesOptions.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCollectionGetEntitiesOptions.cs new file mode 100644 index 0000000000..3fc2633c8a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCollectionGetEntitiesOptions.cs @@ -0,0 +1,57 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.Serialization.cs new file mode 100644 index 0000000000..dcbc54534e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.Serialization.cs @@ -0,0 +1,264 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.cs new file mode 100644 index 0000000000..079151fec3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupCreateOrUpdateContent.cs @@ -0,0 +1,98 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupExpandType.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupExpandType.cs new file mode 100644 index 0000000000..6fd33fdd70 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupExpandType.cs @@ -0,0 +1,54 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupInfo.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupInfo.Serialization.cs new file mode 100644 index 0000000000..497c65bc34 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupInfo.Serialization.cs @@ -0,0 +1,451 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupInfo.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupInfo.cs new file mode 100644 index 0000000000..05985dbcf7 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupInfo.cs @@ -0,0 +1,99 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupListResult.Serialization.cs new file mode 100644 index 0000000000..3d7f50a501 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupListResult.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupListResult.cs new file mode 100644 index 0000000000..814cf13d89 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.Serialization.cs new file mode 100644 index 0000000000..f986e9f7ba --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.Serialization.cs @@ -0,0 +1,144 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.cs new file mode 100644 index 0000000000..cbe681771f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityContent.cs @@ -0,0 +1,67 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.Serialization.cs new file mode 100644 index 0000000000..bde0af8255 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.Serialization.cs @@ -0,0 +1,231 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.cs new file mode 100644 index 0000000000..1c2a592629 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameAvailabilityResult.cs @@ -0,0 +1,76 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.Serialization.cs new file mode 100644 index 0000000000..682fa73fb9 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.Serialization.cs @@ -0,0 +1,28 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.cs new file mode 100644 index 0000000000..71cedf1e26 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupNameUnavailableReason.cs @@ -0,0 +1,18 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.Serialization.cs new file mode 100644 index 0000000000..7210e1adcc --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.Serialization.cs @@ -0,0 +1,151 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.cs new file mode 100644 index 0000000000..13e65d6bf7 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupParentCreateOptions.cs @@ -0,0 +1,76 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPatch.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPatch.Serialization.cs new file mode 100644 index 0000000000..7b047c7af2 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPatch.Serialization.cs @@ -0,0 +1,164 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPatch.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPatch.cs new file mode 100644 index 0000000000..8d3aeabcf3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPatch.cs @@ -0,0 +1,71 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPathElement.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPathElement.Serialization.cs new file mode 100644 index 0000000000..d1c5dae155 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPathElement.Serialization.cs @@ -0,0 +1,204 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPathElement.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPathElement.cs new file mode 100644 index 0000000000..83a547b41a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ManagementGroupPathElement.cs @@ -0,0 +1,71 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ParentManagementGroupInfo.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ParentManagementGroupInfo.Serialization.cs new file mode 100644 index 0000000000..9cc8ebf326 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ParentManagementGroupInfo.Serialization.cs @@ -0,0 +1,238 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ParentManagementGroupInfo.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ParentManagementGroupInfo.cs new file mode 100644 index 0000000000..910a28524a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/Models/ParentManagementGroupInfo.cs @@ -0,0 +1,76 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/ResourceManagerModelFactory.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ResourceManagerModelFactory.cs new file mode 100644 index 0000000000..71c0f3315e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/ResourceManagerModelFactory.cs @@ -0,0 +1,269 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/EntitiesRestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/EntitiesRestOperations.cs new file mode 100644 index 0000000000..e69f3eae1e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/EntitiesRestOperations.cs @@ -0,0 +1,337 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/ManagementGroupSubscriptionsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/ManagementGroupSubscriptionsRestOperations.cs new file mode 100644 index 0000000000..5a9ce3d7e5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/ManagementGroupSubscriptionsRestOperations.cs @@ -0,0 +1,517 @@ +// 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/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/ManagementGroupsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/ManagementGroupsRestOperations.cs new file mode 100644 index 0000000000..f284696f8b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ManagementGroup/Generated/RestOperations/ManagementGroupsRestOperations.cs @@ -0,0 +1,897 @@ +// 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/dotnet-aot-compat/before/Properties/AssemblyInfo.cs b/tests/dotnet/dotnet-aot-compat/before/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000..3a31e4dd1d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +// 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/dotnet-aot-compat/before/ProviderConstants.cs b/tests/dotnet/dotnet-aot-compat/before/ProviderConstants.cs new file mode 100644 index 0000000000..dbce6211e2 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ProviderConstants.cs @@ -0,0 +1,14 @@ +// 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/dotnet-aot-compat/before/RehydrationOperation.cs b/tests/dotnet/dotnet-aot-compat/before/RehydrationOperation.cs new file mode 100644 index 0000000000..7fe620e46e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/RehydrationOperation.cs @@ -0,0 +1,39 @@ +// 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/dotnet-aot-compat/before/RehydrationOperationOfT.cs b/tests/dotnet/dotnet-aot-compat/before/RehydrationOperationOfT.cs new file mode 100644 index 0000000000..21b1298880 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/RehydrationOperationOfT.cs @@ -0,0 +1,42 @@ +// 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/dotnet-aot-compat/before/ResourceManagerExtensions.cs b/tests/dotnet/dotnet-aot-compat/before/ResourceManagerExtensions.cs new file mode 100644 index 0000000000..19a2d39743 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/ResourceManagerExtensions.cs @@ -0,0 +1,50 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/ArmClient.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/ArmClient.cs new file mode 100644 index 0000000000..e26f631cc1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/ArmClient.cs @@ -0,0 +1,26 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/ArmRestApiCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/ArmRestApiCollection.cs new file mode 100644 index 0000000000..25e587549e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/ArmRestApiCollection.cs @@ -0,0 +1,129 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/Extensions/ArmResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Extensions/ArmResource.cs new file mode 100644 index 0000000000..451ced6807 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Extensions/ArmResource.cs @@ -0,0 +1,20 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/FeatureResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/FeatureResource.cs new file mode 100644 index 0000000000..ebfa136947 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/FeatureResource.cs @@ -0,0 +1,26 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/GenericResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/GenericResource.cs new file mode 100644 index 0000000000..7de2f6b25d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/GenericResource.cs @@ -0,0 +1,433 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/GenericResourceCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/GenericResourceCollection.cs new file mode 100644 index 0000000000..ee0a0f75a1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/GenericResourceCollection.cs @@ -0,0 +1,266 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/GenericResourceData.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/GenericResourceData.cs new file mode 100644 index 0000000000..f2bf593f62 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/GenericResourceData.cs @@ -0,0 +1,14 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/HelperSuppressions.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/HelperSuppressions.cs new file mode 100644 index 0000000000..f7cda07595 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/HelperSuppressions.cs @@ -0,0 +1,12 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApi.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApi.Serialization.cs new file mode 100644 index 0000000000..af88ab9534 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApi.Serialization.cs @@ -0,0 +1,159 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApi.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApi.cs new file mode 100644 index 0000000000..164b744651 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApi.cs @@ -0,0 +1,49 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApiListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApiListResult.Serialization.cs new file mode 100644 index 0000000000..ab24d2f204 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApiListResult.Serialization.cs @@ -0,0 +1,40 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApiListResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApiListResult.cs new file mode 100644 index 0000000000..884cd877eb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/ArmRestApiListResult.cs @@ -0,0 +1,32 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/Models/EnforcementMode.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/EnforcementMode.cs new file mode 100644 index 0000000000..ccb5c3feb6 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/EnforcementMode.cs @@ -0,0 +1,20 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/Models/LocationExpanded.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/LocationExpanded.cs new file mode 100644 index 0000000000..e585737abe --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/LocationExpanded.cs @@ -0,0 +1,46 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/Models/LocationMetadata.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/LocationMetadata.cs new file mode 100644 index 0000000000..f266b21d35 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/LocationMetadata.cs @@ -0,0 +1,67 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/Models/ResourcesMoveContent.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/ResourcesMoveContent.cs new file mode 100644 index 0000000000..c63ec6232d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/ResourcesMoveContent.cs @@ -0,0 +1,17 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/Models/ResourcesSku.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/ResourcesSku.cs new file mode 100644 index 0000000000..41b1f3e925 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/ResourcesSku.cs @@ -0,0 +1,14 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/Models/SubResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/SubResource.Serialization.cs new file mode 100644 index 0000000000..c6c9a86519 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/SubResource.Serialization.cs @@ -0,0 +1,112 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/Models/SubResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/SubResource.cs new file mode 100644 index 0000000000..4677811ac4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/SubResource.cs @@ -0,0 +1,36 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/Models/Tag.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/Tag.cs new file mode 100644 index 0000000000..de31694444 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/Tag.cs @@ -0,0 +1,20 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/Models/WritableSubResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/WritableSubResource.Serialization.cs new file mode 100644 index 0000000000..b44b3de3e9 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/WritableSubResource.Serialization.cs @@ -0,0 +1,119 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/Models/WritableSubResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/WritableSubResource.cs new file mode 100644 index 0000000000..105741ada8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/Models/WritableSubResource.cs @@ -0,0 +1,36 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/PolicyAssignmentData.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/PolicyAssignmentData.cs new file mode 100644 index 0000000000..0889491a1a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/PolicyAssignmentData.cs @@ -0,0 +1,48 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/PolicyAssignmentResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/PolicyAssignmentResource.cs new file mode 100644 index 0000000000..b658d222e0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/PolicyAssignmentResource.cs @@ -0,0 +1,96 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/ResourceGroupBuilder.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/ResourceGroupBuilder.cs new file mode 100644 index 0000000000..22cc3f1726 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/ResourceGroupBuilder.cs @@ -0,0 +1,133 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/ResourceGroupCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/ResourceGroupCollection.cs new file mode 100644 index 0000000000..cf7e8bb395 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/ResourceGroupCollection.cs @@ -0,0 +1,39 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/ResourceGroupResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/ResourceGroupResource.cs new file mode 100644 index 0000000000..75c02571f4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/ResourceGroupResource.cs @@ -0,0 +1,110 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/ResourceManagerModelFactory.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/ResourceManagerModelFactory.cs new file mode 100644 index 0000000000..73d3cdd844 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/ResourceManagerModelFactory.cs @@ -0,0 +1,42 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/ResourceProviderCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/ResourceProviderCollection.cs new file mode 100644 index 0000000000..c883e46b6d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/ResourceProviderCollection.cs @@ -0,0 +1,152 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/ResourceProviderData.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/ResourceProviderData.cs new file mode 100644 index 0000000000..7081df7c19 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/ResourceProviderData.cs @@ -0,0 +1,63 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/ResourceProviderResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/ResourceProviderResource.cs new file mode 100644 index 0000000000..d31340bbca --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/ResourceProviderResource.cs @@ -0,0 +1,19 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/RestOperations/RestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/RestOperations/RestOperations.cs new file mode 100644 index 0000000000..9652d2393f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/RestOperations/RestOperations.cs @@ -0,0 +1,107 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/RestOperations/TenantsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/RestOperations/TenantsRestOperations.cs new file mode 100644 index 0000000000..a04a4128ac --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/RestOperations/TenantsRestOperations.cs @@ -0,0 +1,19 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/SubscriptionData.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/SubscriptionData.cs new file mode 100644 index 0000000000..01db245a68 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/SubscriptionData.cs @@ -0,0 +1,18 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/SubscriptionResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/SubscriptionResource.cs new file mode 100644 index 0000000000..db043c39c0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/SubscriptionResource.cs @@ -0,0 +1,118 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/TagResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/TagResource.cs new file mode 100644 index 0000000000..a8e6740e55 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/TagResource.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/TenantCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/TenantCollection.cs new file mode 100644 index 0000000000..9a4f57e413 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/TenantCollection.cs @@ -0,0 +1,28 @@ +// 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/dotnet-aot-compat/before/Resources/Custom/TenantResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/TenantResource.cs new file mode 100644 index 0000000000..6fadc0c833 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Custom/TenantResource.cs @@ -0,0 +1,137 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestCollection.cs new file mode 100644 index 0000000000..3d94174f1d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestCollection.cs @@ -0,0 +1,396 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestData.Serialization.cs new file mode 100644 index 0000000000..ffdbb48171 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestData.Serialization.cs @@ -0,0 +1,647 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestData.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestData.cs new file mode 100644 index 0000000000..32ace96c4d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestData.cs @@ -0,0 +1,117 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestResource.Serialization.cs new file mode 100644 index 0000000000..6c713c5dfe --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestResource.cs new file mode 100644 index 0000000000..62e06308fa --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/DataPolicyManifestResource.cs @@ -0,0 +1,168 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Extensions/ArmClient.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Extensions/ArmClient.cs new file mode 100644 index 0000000000..611e8d348a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Extensions/ArmClient.cs @@ -0,0 +1,183 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Extensions/ArmResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Extensions/ArmResource.cs new file mode 100644 index 0000000000..a70590323b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Extensions/ArmResource.cs @@ -0,0 +1,156 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Extensions/ManagementGroupResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Extensions/ManagementGroupResource.cs new file mode 100644 index 0000000000..2e6a3a5047 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Extensions/ManagementGroupResource.cs @@ -0,0 +1,156 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/FeatureCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/FeatureCollection.cs new file mode 100644 index 0000000000..a0c55991a2 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/FeatureCollection.cs @@ -0,0 +1,394 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/FeatureData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/FeatureData.Serialization.cs new file mode 100644 index 0000000000..5613878760 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/FeatureData.Serialization.cs @@ -0,0 +1,244 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/FeatureData.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/FeatureData.cs new file mode 100644 index 0000000000..ef7d2ec42c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/FeatureData.cs @@ -0,0 +1,81 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/FeatureResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/FeatureResource.Serialization.cs new file mode 100644 index 0000000000..264d1675fc --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/FeatureResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/FeatureResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/FeatureResource.cs new file mode 100644 index 0000000000..463ada11d3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/FeatureResource.cs @@ -0,0 +1,316 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/GenericResourceData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/GenericResourceData.Serialization.cs new file mode 100644 index 0000000000..1f3364c8b0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/GenericResourceData.Serialization.cs @@ -0,0 +1,609 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/GenericResourceData.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/GenericResourceData.cs new file mode 100644 index 0000000000..1440e3dc01 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/GenericResourceData.cs @@ -0,0 +1,121 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Internal/Utf8JsonRequestContent.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Internal/Utf8JsonRequestContent.cs new file mode 100644 index 0000000000..c0ffe14923 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Internal/Utf8JsonRequestContent.cs @@ -0,0 +1,55 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Internal/WirePathAttribute.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Internal/WirePathAttribute.cs new file mode 100644 index 0000000000..4b7cb3247b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Internal/WirePathAttribute.cs @@ -0,0 +1,27 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/GenericResourceOperationSource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/GenericResourceOperationSource.cs new file mode 100644 index 0000000000..f8b70fafa0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/GenericResourceOperationSource.cs @@ -0,0 +1,36 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourceGroupExportResultOperationSource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourceGroupExportResultOperationSource.cs new file mode 100644 index 0000000000..a2603f1e90 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourceGroupExportResultOperationSource.cs @@ -0,0 +1,30 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourcesArmOperation.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourcesArmOperation.cs new file mode 100644 index 0000000000..f3162628f3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourcesArmOperation.cs @@ -0,0 +1,94 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourcesArmOperationOfT.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourcesArmOperationOfT.cs new file mode 100644 index 0000000000..eb320e40da --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/ResourcesArmOperationOfT.cs @@ -0,0 +1,100 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/TagResourceOperationSource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/TagResourceOperationSource.cs new file mode 100644 index 0000000000..452c0702a4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/LongRunningOperation/TagResourceOperationSource.cs @@ -0,0 +1,36 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionCollection.cs new file mode 100644 index 0000000000..a11c7b1d4d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionCollection.cs @@ -0,0 +1,501 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionResource.Serialization.cs new file mode 100644 index 0000000000..867c419838 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionResource.cs new file mode 100644 index 0000000000..f254f2ed5e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicyDefinitionResource.cs @@ -0,0 +1,354 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionCollection.cs new file mode 100644 index 0000000000..e556e58ffa --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionCollection.cs @@ -0,0 +1,501 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionResource.Serialization.cs new file mode 100644 index 0000000000..60c244d59e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionResource.cs new file mode 100644 index 0000000000..4f8ffed49d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementGroupPolicySetDefinitionResource.cs @@ -0,0 +1,354 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ManagementLockCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementLockCollection.cs new file mode 100644 index 0000000000..bb744b2095 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementLockCollection.cs @@ -0,0 +1,488 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ManagementLockData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementLockData.Serialization.cs new file mode 100644 index 0000000000..1468da3f30 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementLockData.Serialization.cs @@ -0,0 +1,334 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ManagementLockData.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementLockData.cs new file mode 100644 index 0000000000..64c9e5d2cd --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementLockData.cs @@ -0,0 +1,94 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ManagementLockResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementLockResource.Serialization.cs new file mode 100644 index 0000000000..3dfbf0b23b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementLockResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ManagementLockResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementLockResource.cs new file mode 100644 index 0000000000..e02de890dd --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ManagementLockResource.cs @@ -0,0 +1,353 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ApiProfile.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ApiProfile.Serialization.cs new file mode 100644 index 0000000000..e10abbf84b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ApiProfile.Serialization.cs @@ -0,0 +1,204 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ApiProfile.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ApiProfile.cs new file mode 100644 index 0000000000..f739455520 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ApiProfile.cs @@ -0,0 +1,71 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameter.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameter.Serialization.cs new file mode 100644 index 0000000000..8c48aed370 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameter.Serialization.cs @@ -0,0 +1,306 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameter.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameter.cs new file mode 100644 index 0000000000..9eb8280256 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameter.cs @@ -0,0 +1,140 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterType.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterType.cs new file mode 100644 index 0000000000..c0dee9c68a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterType.cs @@ -0,0 +1,66 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterValue.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterValue.Serialization.cs new file mode 100644 index 0000000000..2612dbb29e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterValue.Serialization.cs @@ -0,0 +1,173 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterValue.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterValue.cs new file mode 100644 index 0000000000..0e055d7eb1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ArmPolicyParameterValue.cs @@ -0,0 +1,95 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/AvailabilityZoneMappings.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/AvailabilityZoneMappings.Serialization.cs new file mode 100644 index 0000000000..ac779501aa --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/AvailabilityZoneMappings.Serialization.cs @@ -0,0 +1,204 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/AvailabilityZoneMappings.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/AvailabilityZoneMappings.cs new file mode 100644 index 0000000000..98f10092e5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/AvailabilityZoneMappings.cs @@ -0,0 +1,71 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/AzureRoleDefinition.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/AzureRoleDefinition.Serialization.cs new file mode 100644 index 0000000000..e62dc5dae7 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/AzureRoleDefinition.Serialization.cs @@ -0,0 +1,351 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/AzureRoleDefinition.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/AzureRoleDefinition.cs new file mode 100644 index 0000000000..f770872147 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/AzureRoleDefinition.cs @@ -0,0 +1,88 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.Serialization.cs new file mode 100644 index 0000000000..5577ee1465 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.Serialization.cs @@ -0,0 +1,293 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.cs new file mode 100644 index 0000000000..4f66f5b04c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/DataManifestCustomResourceFunctionDefinition.cs @@ -0,0 +1,83 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestEffect.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestEffect.Serialization.cs new file mode 100644 index 0000000000..3556bcce27 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestEffect.Serialization.cs @@ -0,0 +1,207 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestEffect.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestEffect.cs new file mode 100644 index 0000000000..140fcae664 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestEffect.cs @@ -0,0 +1,100 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestListResult.Serialization.cs new file mode 100644 index 0000000000..8e5ca3b53f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestListResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestListResult.cs new file mode 100644 index 0000000000..769a87638b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/DataPolicyManifestListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/EnforcementMode.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/EnforcementMode.cs new file mode 100644 index 0000000000..239bc9da67 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/EnforcementMode.cs @@ -0,0 +1,51 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ExportTemplate.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ExportTemplate.Serialization.cs new file mode 100644 index 0000000000..8d4f146fb5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ExportTemplate.Serialization.cs @@ -0,0 +1,154 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ExportTemplate.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ExportTemplate.cs new file mode 100644 index 0000000000..43ce04a802 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ExportTemplate.cs @@ -0,0 +1,72 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocation.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocation.Serialization.cs new file mode 100644 index 0000000000..d3763ccf2d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocation.Serialization.cs @@ -0,0 +1,194 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocation.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocation.cs new file mode 100644 index 0000000000..c052d4f1e8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocation.cs @@ -0,0 +1,39 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocationType.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocationType.cs new file mode 100644 index 0000000000..76cfe6ccdb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ExtendedLocationType.cs @@ -0,0 +1,48 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/FeatureOperationsListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/FeatureOperationsListResult.Serialization.cs new file mode 100644 index 0000000000..d1afa4568e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/FeatureOperationsListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/FeatureOperationsListResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/FeatureOperationsListResult.cs new file mode 100644 index 0000000000..e2063f4235 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/FeatureOperationsListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/FeatureProperties.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/FeatureProperties.Serialization.cs new file mode 100644 index 0000000000..b9de6a882e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/FeatureProperties.Serialization.cs @@ -0,0 +1,170 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/FeatureProperties.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/FeatureProperties.cs new file mode 100644 index 0000000000..bab8758f08 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/FeatureProperties.cs @@ -0,0 +1,66 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/LocationExpanded.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/LocationExpanded.Serialization.cs new file mode 100644 index 0000000000..0ea0b73f73 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/LocationExpanded.Serialization.cs @@ -0,0 +1,409 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/LocationExpanded.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/LocationExpanded.cs new file mode 100644 index 0000000000..60e4a76f90 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/LocationExpanded.cs @@ -0,0 +1,102 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/LocationListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/LocationListResult.Serialization.cs new file mode 100644 index 0000000000..d497dbadaf --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/LocationListResult.Serialization.cs @@ -0,0 +1,185 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/LocationListResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/LocationListResult.cs new file mode 100644 index 0000000000..a614638e72 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/LocationListResult.cs @@ -0,0 +1,66 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/LocationMetadata.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/LocationMetadata.Serialization.cs new file mode 100644 index 0000000000..7f29d1a639 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/LocationMetadata.Serialization.cs @@ -0,0 +1,443 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/LocationMetadata.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/LocationMetadata.cs new file mode 100644 index 0000000000..4fe985db7d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/LocationMetadata.cs @@ -0,0 +1,101 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/LocationType.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/LocationType.Serialization.cs new file mode 100644 index 0000000000..95769ed54d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/LocationType.Serialization.cs @@ -0,0 +1,28 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/LocationType.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/LocationType.cs new file mode 100644 index 0000000000..fe985afe37 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/LocationType.cs @@ -0,0 +1,18 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ManagedByTenant.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ManagedByTenant.Serialization.cs new file mode 100644 index 0000000000..e9c97cb3ba --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ManagedByTenant.Serialization.cs @@ -0,0 +1,166 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ManagedByTenant.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ManagedByTenant.cs new file mode 100644 index 0000000000..17afaec3ad --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ManagedByTenant.cs @@ -0,0 +1,66 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockLevel.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockLevel.cs new file mode 100644 index 0000000000..f3f6fa4cf8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockLevel.cs @@ -0,0 +1,54 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockListResult.Serialization.cs new file mode 100644 index 0000000000..5d7754328f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockListResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockListResult.cs new file mode 100644 index 0000000000..7702747e45 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockOwner.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockOwner.Serialization.cs new file mode 100644 index 0000000000..36a902f6d0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockOwner.Serialization.cs @@ -0,0 +1,170 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockOwner.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockOwner.cs new file mode 100644 index 0000000000..7cb1045193 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ManagementLockOwner.cs @@ -0,0 +1,66 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/NonComplianceMessage.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/NonComplianceMessage.Serialization.cs new file mode 100644 index 0000000000..70428e4798 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/NonComplianceMessage.Serialization.cs @@ -0,0 +1,201 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/NonComplianceMessage.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/NonComplianceMessage.cs new file mode 100644 index 0000000000..a412852eaa --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/NonComplianceMessage.cs @@ -0,0 +1,81 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PairedRegion.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PairedRegion.Serialization.cs new file mode 100644 index 0000000000..8625021fca --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PairedRegion.Serialization.cs @@ -0,0 +1,238 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PairedRegion.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PairedRegion.cs new file mode 100644 index 0000000000..b4e30a1a8f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PairedRegion.cs @@ -0,0 +1,76 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ParameterDefinitionsValueMetadata.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ParameterDefinitionsValueMetadata.Serialization.cs new file mode 100644 index 0000000000..d8c4cc28c1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ParameterDefinitionsValueMetadata.Serialization.cs @@ -0,0 +1,263 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ParameterDefinitionsValueMetadata.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ParameterDefinitionsValueMetadata.cs new file mode 100644 index 0000000000..96ed7496b1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ParameterDefinitionsValueMetadata.cs @@ -0,0 +1,82 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/Permission.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/Permission.Serialization.cs new file mode 100644 index 0000000000..6c03d93972 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/Permission.Serialization.cs @@ -0,0 +1,381 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/Permission.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/Permission.cs new file mode 100644 index 0000000000..0b614bc2dd --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/Permission.cs @@ -0,0 +1,85 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentListResult.Serialization.cs new file mode 100644 index 0000000000..3e3080735e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentListResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentListResult.cs new file mode 100644 index 0000000000..2c650f257a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentPatch.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentPatch.Serialization.cs new file mode 100644 index 0000000000..57fee5d8fd --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentPatch.Serialization.cs @@ -0,0 +1,214 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentPatch.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentPatch.cs new file mode 100644 index 0000000000..d85c3fcbad --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyAssignmentPatch.cs @@ -0,0 +1,85 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionGroup.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionGroup.Serialization.cs new file mode 100644 index 0000000000..bcffda6463 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionGroup.Serialization.cs @@ -0,0 +1,309 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionGroup.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionGroup.cs new file mode 100644 index 0000000000..9f18d09866 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionGroup.cs @@ -0,0 +1,96 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionListResult.Serialization.cs new file mode 100644 index 0000000000..f0b97f4bac --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionListResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionListResult.cs new file mode 100644 index 0000000000..c09165e0d9 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionReference.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionReference.Serialization.cs new file mode 100644 index 0000000000..c1d6ceb7ba --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionReference.Serialization.cs @@ -0,0 +1,313 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionReference.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionReference.cs new file mode 100644 index 0000000000..da023f91ac --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyDefinitionReference.cs @@ -0,0 +1,93 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverride.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverride.Serialization.cs new file mode 100644 index 0000000000..ac3756baff --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverride.Serialization.cs @@ -0,0 +1,249 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverride.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverride.cs new file mode 100644 index 0000000000..d546bbcfa3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverride.cs @@ -0,0 +1,77 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverrideKind.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverrideKind.cs new file mode 100644 index 0000000000..1529755b23 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyOverrideKind.cs @@ -0,0 +1,48 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PolicySetDefinitionListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicySetDefinitionListResult.Serialization.cs new file mode 100644 index 0000000000..dd8370379d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicySetDefinitionListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PolicySetDefinitionListResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicySetDefinitionListResult.cs new file mode 100644 index 0000000000..7077003141 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicySetDefinitionListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PolicyType.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyType.cs new file mode 100644 index 0000000000..9f88c1c72e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PolicyType.cs @@ -0,0 +1,57 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTag.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTag.Serialization.cs new file mode 100644 index 0000000000..40ff878479 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTag.Serialization.cs @@ -0,0 +1,283 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTag.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTag.cs new file mode 100644 index 0000000000..a929577cd8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTag.cs @@ -0,0 +1,82 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagCount.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagCount.Serialization.cs new file mode 100644 index 0000000000..0b640a7ed9 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagCount.Serialization.cs @@ -0,0 +1,200 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagCount.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagCount.cs new file mode 100644 index 0000000000..b7d6360ac8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagCount.cs @@ -0,0 +1,71 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagValue.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagValue.Serialization.cs new file mode 100644 index 0000000000..53ab84ffc9 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagValue.Serialization.cs @@ -0,0 +1,234 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagValue.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagValue.cs new file mode 100644 index 0000000000..7c91e6cc59 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagValue.cs @@ -0,0 +1,76 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagsListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagsListResult.Serialization.cs new file mode 100644 index 0000000000..d3a49bc520 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagsListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagsListResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagsListResult.cs new file mode 100644 index 0000000000..dc4cc163ff --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/PredefinedTagsListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ProviderAuthorizationConsentState.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderAuthorizationConsentState.cs new file mode 100644 index 0000000000..70a7ad1aa3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderAuthorizationConsentState.cs @@ -0,0 +1,57 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ProviderConsentDefinition.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderConsentDefinition.Serialization.cs new file mode 100644 index 0000000000..3dcd030070 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderConsentDefinition.Serialization.cs @@ -0,0 +1,133 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ProviderConsentDefinition.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderConsentDefinition.cs new file mode 100644 index 0000000000..92b4c29858 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderConsentDefinition.cs @@ -0,0 +1,66 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ProviderExtendedLocation.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderExtendedLocation.Serialization.cs new file mode 100644 index 0000000000..f6edb22cb3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderExtendedLocation.Serialization.cs @@ -0,0 +1,262 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ProviderExtendedLocation.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderExtendedLocation.cs new file mode 100644 index 0000000000..3b129aeeb0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderExtendedLocation.cs @@ -0,0 +1,78 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermission.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermission.Serialization.cs new file mode 100644 index 0000000000..25e7bc3b01 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermission.Serialization.cs @@ -0,0 +1,260 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermission.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermission.cs new file mode 100644 index 0000000000..b8dbd24538 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermission.cs @@ -0,0 +1,81 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermissionListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermissionListResult.Serialization.cs new file mode 100644 index 0000000000..c2577692c4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermissionListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermissionListResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermissionListResult.cs new file mode 100644 index 0000000000..bfb5b6bbb2 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderPermissionListResult.cs @@ -0,0 +1,72 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ProviderRegistrationContent.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderRegistrationContent.Serialization.cs new file mode 100644 index 0000000000..bf15b0087f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderRegistrationContent.Serialization.cs @@ -0,0 +1,133 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ProviderRegistrationContent.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderRegistrationContent.cs new file mode 100644 index 0000000000..92eb16dbd6 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderRegistrationContent.cs @@ -0,0 +1,77 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceType.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceType.Serialization.cs new file mode 100644 index 0000000000..2aec022a34 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceType.Serialization.cs @@ -0,0 +1,627 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceType.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceType.cs new file mode 100644 index 0000000000..64234b3ba9 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceType.cs @@ -0,0 +1,118 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceTypeListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceTypeListResult.Serialization.cs new file mode 100644 index 0000000000..c8cb061afb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceTypeListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceTypeListResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceTypeListResult.cs new file mode 100644 index 0000000000..e58854a89d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ProviderResourceTypeListResult.cs @@ -0,0 +1,72 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/RegionCategory.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/RegionCategory.cs new file mode 100644 index 0000000000..4f94df158a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/RegionCategory.cs @@ -0,0 +1,54 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/RegionType.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/RegionType.cs new file mode 100644 index 0000000000..b78f1316be --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/RegionType.cs @@ -0,0 +1,51 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupExportResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupExportResult.Serialization.cs new file mode 100644 index 0000000000..0c3a290f82 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupExportResult.Serialization.cs @@ -0,0 +1,203 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupExportResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupExportResult.cs new file mode 100644 index 0000000000..b6a5fd70bd --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupExportResult.cs @@ -0,0 +1,100 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupListResult.Serialization.cs new file mode 100644 index 0000000000..9d18acd599 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupListResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupListResult.cs new file mode 100644 index 0000000000..aad563b999 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupPatch.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupPatch.Serialization.cs new file mode 100644 index 0000000000..37de7fd731 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupPatch.Serialization.cs @@ -0,0 +1,181 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupPatch.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupPatch.cs new file mode 100644 index 0000000000..b10e558b03 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupPatch.cs @@ -0,0 +1,88 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupProperties.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupProperties.Serialization.cs new file mode 100644 index 0000000000..4ecf59e702 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupProperties.Serialization.cs @@ -0,0 +1,170 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupProperties.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupProperties.cs new file mode 100644 index 0000000000..b62fad0a7f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceGroupProperties.cs @@ -0,0 +1,66 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceListResult.Serialization.cs new file mode 100644 index 0000000000..f5e92f7eaa --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceListResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceListResult.cs new file mode 100644 index 0000000000..6d1d19e150 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationContent.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationContent.Serialization.cs new file mode 100644 index 0000000000..1ea0840131 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationContent.Serialization.cs @@ -0,0 +1,134 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationContent.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationContent.cs new file mode 100644 index 0000000000..e3886a6c2f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationContent.cs @@ -0,0 +1,84 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationResult.Serialization.cs new file mode 100644 index 0000000000..46ee78b1e3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationResult.Serialization.cs @@ -0,0 +1,230 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationResult.cs new file mode 100644 index 0000000000..7e0501f862 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationResult.cs @@ -0,0 +1,77 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationStatus.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationStatus.cs new file mode 100644 index 0000000000..78a1b378f1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceNameValidationStatus.cs @@ -0,0 +1,51 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceProviderListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceProviderListResult.Serialization.cs new file mode 100644 index 0000000000..e8668c7885 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceProviderListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceProviderListResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceProviderListResult.cs new file mode 100644 index 0000000000..1049d3073b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceProviderListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelector.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelector.Serialization.cs new file mode 100644 index 0000000000..68ac0784f5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelector.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelector.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelector.cs new file mode 100644 index 0000000000..e85c7541cb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelector.cs @@ -0,0 +1,72 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorExpression.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorExpression.Serialization.cs new file mode 100644 index 0000000000..78c6046176 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorExpression.Serialization.cs @@ -0,0 +1,289 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorExpression.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorExpression.cs new file mode 100644 index 0000000000..c10dad80a6 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorExpression.cs @@ -0,0 +1,78 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorKind.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorKind.cs new file mode 100644 index 0000000000..bed65e9a77 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceSelectorKind.cs @@ -0,0 +1,57 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAlias.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAlias.Serialization.cs new file mode 100644 index 0000000000..6e05a2234c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAlias.Serialization.cs @@ -0,0 +1,350 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAlias.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAlias.cs new file mode 100644 index 0000000000..26ac43a913 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAlias.cs @@ -0,0 +1,92 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPath.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPath.Serialization.cs new file mode 100644 index 0000000000..bf32500a35 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPath.Serialization.cs @@ -0,0 +1,292 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPath.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPath.cs new file mode 100644 index 0000000000..acd74e09e7 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPath.cs @@ -0,0 +1,82 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathAttributes.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathAttributes.cs new file mode 100644 index 0000000000..217d95e60d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathAttributes.cs @@ -0,0 +1,51 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathMetadata.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathMetadata.Serialization.cs new file mode 100644 index 0000000000..a4f23ac02b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathMetadata.Serialization.cs @@ -0,0 +1,196 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathMetadata.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathMetadata.cs new file mode 100644 index 0000000000..1a4b48937b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathMetadata.cs @@ -0,0 +1,71 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathTokenType.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathTokenType.cs new file mode 100644 index 0000000000..98fd72b001 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPathTokenType.cs @@ -0,0 +1,69 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPattern.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPattern.Serialization.cs new file mode 100644 index 0000000000..ed9f763b2d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPattern.Serialization.cs @@ -0,0 +1,234 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPattern.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPattern.cs new file mode 100644 index 0000000000..5c318a2dde --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPattern.cs @@ -0,0 +1,76 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPatternType.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPatternType.Serialization.cs new file mode 100644 index 0000000000..8faaf01391 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPatternType.Serialization.cs @@ -0,0 +1,28 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPatternType.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPatternType.cs new file mode 100644 index 0000000000..8ed0430db1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasPatternType.cs @@ -0,0 +1,18 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasType.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasType.Serialization.cs new file mode 100644 index 0000000000..2ddd82d437 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasType.Serialization.cs @@ -0,0 +1,30 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasType.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasType.cs new file mode 100644 index 0000000000..b111828d70 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliasType.cs @@ -0,0 +1,20 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliases.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliases.Serialization.cs new file mode 100644 index 0000000000..96f55ab14c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliases.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliases.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliases.cs new file mode 100644 index 0000000000..872c369df5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourceTypeAliases.cs @@ -0,0 +1,72 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesMoveContent.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesMoveContent.Serialization.cs new file mode 100644 index 0000000000..88cd1fb383 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesMoveContent.Serialization.cs @@ -0,0 +1,158 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesMoveContent.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesMoveContent.cs new file mode 100644 index 0000000000..89139c1b2e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesMoveContent.cs @@ -0,0 +1,73 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesSku.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesSku.Serialization.cs new file mode 100644 index 0000000000..9b3032a656 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesSku.Serialization.cs @@ -0,0 +1,343 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesSku.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesSku.cs new file mode 100644 index 0000000000..1aa8907276 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ResourcesSku.cs @@ -0,0 +1,91 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/SpendingLimit.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/SpendingLimit.Serialization.cs new file mode 100644 index 0000000000..1330415ea3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/SpendingLimit.Serialization.cs @@ -0,0 +1,30 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/SpendingLimit.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/SpendingLimit.cs new file mode 100644 index 0000000000..f1cf361866 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/SpendingLimit.cs @@ -0,0 +1,20 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/SubResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/SubResource.cs new file mode 100644 index 0000000000..b5bc3d1195 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/SubResource.cs @@ -0,0 +1,58 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionListResult.Serialization.cs new file mode 100644 index 0000000000..243808a807 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionListResult.Serialization.cs @@ -0,0 +1,216 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionListResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionListResult.cs new file mode 100644 index 0000000000..62586d3820 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionListResult.cs @@ -0,0 +1,80 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionPolicies.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionPolicies.Serialization.cs new file mode 100644 index 0000000000..9b072238de --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionPolicies.Serialization.cs @@ -0,0 +1,234 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionPolicies.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionPolicies.cs new file mode 100644 index 0000000000..e953221105 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionPolicies.cs @@ -0,0 +1,76 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionState.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionState.Serialization.cs new file mode 100644 index 0000000000..51a2212e62 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionState.Serialization.cs @@ -0,0 +1,34 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionState.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionState.cs new file mode 100644 index 0000000000..2c58d11912 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/SubscriptionState.cs @@ -0,0 +1,24 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/Tag.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/Tag.Serialization.cs new file mode 100644 index 0000000000..9282f0649a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/Tag.Serialization.cs @@ -0,0 +1,200 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/Tag.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/Tag.cs new file mode 100644 index 0000000000..694808ed76 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/Tag.cs @@ -0,0 +1,63 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/TagPatchMode.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TagPatchMode.cs new file mode 100644 index 0000000000..a9f204e236 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TagPatchMode.cs @@ -0,0 +1,54 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/TagResourcePatch.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TagResourcePatch.Serialization.cs new file mode 100644 index 0000000000..3b4d3c7772 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TagResourcePatch.Serialization.cs @@ -0,0 +1,148 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/TagResourcePatch.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TagResourcePatch.cs new file mode 100644 index 0000000000..dc4496a3c0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TagResourcePatch.cs @@ -0,0 +1,81 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/TenantCategory.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TenantCategory.Serialization.cs new file mode 100644 index 0000000000..a3d824a90a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TenantCategory.Serialization.cs @@ -0,0 +1,30 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/TenantCategory.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TenantCategory.cs new file mode 100644 index 0000000000..4de42a1b2f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TenantCategory.cs @@ -0,0 +1,20 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/TenantListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TenantListResult.Serialization.cs new file mode 100644 index 0000000000..2f42b18f55 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TenantListResult.Serialization.cs @@ -0,0 +1,216 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/TenantListResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TenantListResult.cs new file mode 100644 index 0000000000..82c47daaf1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TenantListResult.cs @@ -0,0 +1,80 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProvider.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProvider.Serialization.cs new file mode 100644 index 0000000000..200c7232ad --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProvider.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProvider.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProvider.cs new file mode 100644 index 0000000000..c32fa3cc1a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProvider.cs @@ -0,0 +1,72 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProviderListResult.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProviderListResult.Serialization.cs new file mode 100644 index 0000000000..29cfc732a4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProviderListResult.Serialization.cs @@ -0,0 +1,219 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProviderListResult.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProviderListResult.cs new file mode 100644 index 0000000000..44043f0767 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TenantResourceProviderListResult.cs @@ -0,0 +1,70 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/TrackedResourceExtendedData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TrackedResourceExtendedData.Serialization.cs new file mode 100644 index 0000000000..ab343d86e9 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TrackedResourceExtendedData.Serialization.cs @@ -0,0 +1,313 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/TrackedResourceExtendedData.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TrackedResourceExtendedData.cs new file mode 100644 index 0000000000..1474b682eb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/TrackedResourceExtendedData.cs @@ -0,0 +1,80 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ZoneMapping.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ZoneMapping.Serialization.cs new file mode 100644 index 0000000000..7d0844bc01 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ZoneMapping.Serialization.cs @@ -0,0 +1,228 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/Models/ZoneMapping.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ZoneMapping.cs new file mode 100644 index 0000000000..78773bb967 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/Models/ZoneMapping.cs @@ -0,0 +1,73 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentCollection.cs new file mode 100644 index 0000000000..c424f0598d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentCollection.cs @@ -0,0 +1,630 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentData.Serialization.cs new file mode 100644 index 0000000000..75d365aacf --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentData.Serialization.cs @@ -0,0 +1,760 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentData.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentData.cs new file mode 100644 index 0000000000..f0a246cdc3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentData.cs @@ -0,0 +1,170 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentResource.Serialization.cs new file mode 100644 index 0000000000..407fb6014f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentResource.cs new file mode 100644 index 0000000000..be2bed645c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/PolicyAssignmentResource.cs @@ -0,0 +1,342 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/PolicyDefinitionData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/PolicyDefinitionData.Serialization.cs new file mode 100644 index 0000000000..0e82e86edf --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/PolicyDefinitionData.Serialization.cs @@ -0,0 +1,492 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/PolicyDefinitionData.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/PolicyDefinitionData.cs new file mode 100644 index 0000000000..6689f9af87 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/PolicyDefinitionData.cs @@ -0,0 +1,165 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/PolicySetDefinitionData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/PolicySetDefinitionData.Serialization.cs new file mode 100644 index 0000000000..f4122f7af1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/PolicySetDefinitionData.Serialization.cs @@ -0,0 +1,517 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/PolicySetDefinitionData.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/PolicySetDefinitionData.cs new file mode 100644 index 0000000000..22dae46c74 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/PolicySetDefinitionData.cs @@ -0,0 +1,138 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ResourceGroupCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceGroupCollection.cs new file mode 100644 index 0000000000..6fa5910de7 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceGroupCollection.cs @@ -0,0 +1,500 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ResourceGroupData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceGroupData.Serialization.cs new file mode 100644 index 0000000000..421513f67e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceGroupData.Serialization.cs @@ -0,0 +1,352 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ResourceGroupData.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceGroupData.cs new file mode 100644 index 0000000000..86a684655c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceGroupData.cs @@ -0,0 +1,95 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ResourceGroupResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceGroupResource.Serialization.cs new file mode 100644 index 0000000000..65a084b9bc --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceGroupResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ResourceGroupResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceGroupResource.cs new file mode 100644 index 0000000000..049966950d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceGroupResource.cs @@ -0,0 +1,980 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ResourceManagerModelFactory.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceManagerModelFactory.cs new file mode 100644 index 0000000000..c17962de61 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceManagerModelFactory.cs @@ -0,0 +1,764 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ResourceProviderCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceProviderCollection.cs new file mode 100644 index 0000000000..5915ae4051 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceProviderCollection.cs @@ -0,0 +1,389 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ResourceProviderData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceProviderData.Serialization.cs new file mode 100644 index 0000000000..3b5cd61eb0 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceProviderData.Serialization.cs @@ -0,0 +1,355 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ResourceProviderData.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceProviderData.cs new file mode 100644 index 0000000000..e18d3655a2 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceProviderData.cs @@ -0,0 +1,87 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ResourceProviderResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceProviderResource.Serialization.cs new file mode 100644 index 0000000000..cff873e5de --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceProviderResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/ResourceProviderResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceProviderResource.cs new file mode 100644 index 0000000000..1644e4e793 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/ResourceProviderResource.cs @@ -0,0 +1,509 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/RestOperations/DataPolicyManifestsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/DataPolicyManifestsRestOperations.cs new file mode 100644 index 0000000000..b94f641cd7 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/DataPolicyManifestsRestOperations.cs @@ -0,0 +1,265 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/RestOperations/FeaturesRestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/FeaturesRestOperations.cs new file mode 100644 index 0000000000..6eda9037c4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/FeaturesRestOperations.cs @@ -0,0 +1,643 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/RestOperations/ManagementLocksRestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/ManagementLocksRestOperations.cs new file mode 100644 index 0000000000..66b3dc6664 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/ManagementLocksRestOperations.cs @@ -0,0 +1,459 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicyAssignmentsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicyAssignmentsRestOperations.cs new file mode 100644 index 0000000000..8437bfbc9f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicyAssignmentsRestOperations.cs @@ -0,0 +1,1183 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicyDefinitionsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicyDefinitionsRestOperations.cs new file mode 100644 index 0000000000..d8a8f6ee24 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicyDefinitionsRestOperations.cs @@ -0,0 +1,1145 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicySetDefinitionsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicySetDefinitionsRestOperations.cs new file mode 100644 index 0000000000..74741a5519 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/PolicySetDefinitionsRestOperations.cs @@ -0,0 +1,1149 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/RestOperations/ProviderResourceTypesRestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/ProviderResourceTypesRestOperations.cs new file mode 100644 index 0000000000..3acae9da9e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/ProviderResourceTypesRestOperations.cs @@ -0,0 +1,135 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/RestOperations/ProvidersRestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/ProvidersRestOperations.cs new file mode 100644 index 0000000000..63f444d6e3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/ProvidersRestOperations.cs @@ -0,0 +1,802 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourceGroupsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourceGroupsRestOperations.cs new file mode 100644 index 0000000000..06b9758562 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourceGroupsRestOperations.cs @@ -0,0 +1,663 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourceManagementRestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourceManagementRestOperations.cs new file mode 100644 index 0000000000..490f691f55 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourceManagementRestOperations.cs @@ -0,0 +1,112 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourcesRestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourcesRestOperations.cs new file mode 100644 index 0000000000..c990c23b40 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/ResourcesRestOperations.cs @@ -0,0 +1,915 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/RestOperations/SubscriptionsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/SubscriptionsRestOperations.cs new file mode 100644 index 0000000000..a5f94cca14 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/SubscriptionsRestOperations.cs @@ -0,0 +1,341 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/RestOperations/TagsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/TagsRestOperations.cs new file mode 100644 index 0000000000..ac7c58fb5a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/TagsRestOperations.cs @@ -0,0 +1,833 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/RestOperations/TenantsRestOperations.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/TenantsRestOperations.cs new file mode 100644 index 0000000000..25264b970e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/RestOperations/TenantsRestOperations.cs @@ -0,0 +1,182 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/SubscriptionCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionCollection.cs new file mode 100644 index 0000000000..8ff124397b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionCollection.cs @@ -0,0 +1,394 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/SubscriptionData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionData.Serialization.cs new file mode 100644 index 0000000000..44b32c32c3 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionData.Serialization.cs @@ -0,0 +1,481 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/SubscriptionData.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionData.cs new file mode 100644 index 0000000000..02537ef7b6 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionData.cs @@ -0,0 +1,109 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionCollection.cs new file mode 100644 index 0000000000..e0e348db73 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionCollection.cs @@ -0,0 +1,500 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionResource.Serialization.cs new file mode 100644 index 0000000000..d98f9066c1 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionResource.cs new file mode 100644 index 0000000000..415bda5437 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicyDefinitionResource.cs @@ -0,0 +1,353 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionCollection.cs new file mode 100644 index 0000000000..3f7c59a96f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionCollection.cs @@ -0,0 +1,500 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionResource.Serialization.cs new file mode 100644 index 0000000000..2c9efcff84 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionResource.cs new file mode 100644 index 0000000000..9bf306c256 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionPolicySetDefinitionResource.cs @@ -0,0 +1,353 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/SubscriptionResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionResource.Serialization.cs new file mode 100644 index 0000000000..138601640e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/SubscriptionResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionResource.cs new file mode 100644 index 0000000000..e484fd200a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/SubscriptionResource.cs @@ -0,0 +1,962 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/TagResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TagResource.Serialization.cs new file mode 100644 index 0000000000..14b43eb7c4 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TagResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/TagResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TagResource.cs new file mode 100644 index 0000000000..f63e4775de --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TagResource.cs @@ -0,0 +1,437 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/TagResourceData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TagResourceData.Serialization.cs new file mode 100644 index 0000000000..29ce35e544 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TagResourceData.Serialization.cs @@ -0,0 +1,237 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/TagResourceData.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TagResourceData.cs new file mode 100644 index 0000000000..8bda3dfa58 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TagResourceData.cs @@ -0,0 +1,96 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/TenantCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantCollection.cs new file mode 100644 index 0000000000..53cd523d8b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantCollection.cs @@ -0,0 +1,199 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/TenantData.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantData.Serialization.cs new file mode 100644 index 0000000000..4449446703 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantData.Serialization.cs @@ -0,0 +1,504 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/TenantData.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantData.cs new file mode 100644 index 0000000000..7d91999217 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantData.cs @@ -0,0 +1,116 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionCollection.cs new file mode 100644 index 0000000000..bd817fab6a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionCollection.cs @@ -0,0 +1,398 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionResource.Serialization.cs new file mode 100644 index 0000000000..6d08620cc8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionResource.cs new file mode 100644 index 0000000000..a8464ce670 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantPolicyDefinitionResource.cs @@ -0,0 +1,168 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionCollection.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionCollection.cs new file mode 100644 index 0000000000..dbc7feb42d --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionCollection.cs @@ -0,0 +1,398 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionResource.Serialization.cs new file mode 100644 index 0000000000..e2e25a534c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionResource.cs new file mode 100644 index 0000000000..ca45c6dc6a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantPolicySetDefinitionResource.cs @@ -0,0 +1,168 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/TenantResource.Serialization.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantResource.Serialization.cs new file mode 100644 index 0000000000..7b9b360a83 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantResource.Serialization.cs @@ -0,0 +1,29 @@ +// 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/dotnet-aot-compat/before/Resources/Generated/TenantResource.cs b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantResource.cs new file mode 100644 index 0000000000..1b1536a286 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Resources/Generated/TenantResource.cs @@ -0,0 +1,505 @@ +// 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/dotnet-aot-compat/before/Shared/AppContextSwitchHelper.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/AppContextSwitchHelper.cs new file mode 100644 index 0000000000..6b511aae6c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/AppContextSwitchHelper.cs @@ -0,0 +1,42 @@ +// 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/dotnet-aot-compat/before/Shared/AsyncLockWithValue.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/AsyncLockWithValue.cs new file mode 100644 index 0000000000..96aa1a559c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/AsyncLockWithValue.cs @@ -0,0 +1,260 @@ +// 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/dotnet-aot-compat/before/Shared/AzureResourceProviderNamespaceAttribute.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/AzureResourceProviderNamespaceAttribute.cs new file mode 100644 index 0000000000..e9ac665a94 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/AzureResourceProviderNamespaceAttribute.cs @@ -0,0 +1,22 @@ +// 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/dotnet-aot-compat/before/Shared/ClientDiagnostics.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/ClientDiagnostics.cs new file mode 100644 index 0000000000..f9fc345937 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/ClientDiagnostics.cs @@ -0,0 +1,73 @@ +// 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/dotnet-aot-compat/before/Shared/DiagnosticScope.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/DiagnosticScope.cs new file mode 100644 index 0000000000..c32bf2b8cb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/DiagnosticScope.cs @@ -0,0 +1,448 @@ +// 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/dotnet-aot-compat/before/Shared/DiagnosticScopeFactory.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/DiagnosticScopeFactory.cs new file mode 100644 index 0000000000..5e1d9c556e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/DiagnosticScopeFactory.cs @@ -0,0 +1,103 @@ +// 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/dotnet-aot-compat/before/Shared/FixedDelayWithNoJitterStrategy.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/FixedDelayWithNoJitterStrategy.cs new file mode 100644 index 0000000000..1051e56b3f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/FixedDelayWithNoJitterStrategy.cs @@ -0,0 +1,26 @@ +// 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/dotnet-aot-compat/before/Shared/ForwardsClientCallsAttribute.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/ForwardsClientCallsAttribute.cs new file mode 100644 index 0000000000..e9e933541b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/ForwardsClientCallsAttribute.cs @@ -0,0 +1,39 @@ +// 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/dotnet-aot-compat/before/Shared/HashCodeBuilder.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/HashCodeBuilder.cs new file mode 100644 index 0000000000..a6a76f93f8 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/HashCodeBuilder.cs @@ -0,0 +1,387 @@ +// 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/dotnet-aot-compat/before/Shared/HttpMessageSanitizer.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/HttpMessageSanitizer.cs new file mode 100644 index 0000000000..36becf22a5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/HttpMessageSanitizer.cs @@ -0,0 +1,198 @@ +// 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/dotnet-aot-compat/before/Shared/HttpPipelineExtensions.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/HttpPipelineExtensions.cs new file mode 100644 index 0000000000..231f13cf53 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/HttpPipelineExtensions.cs @@ -0,0 +1,110 @@ +// 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/dotnet-aot-compat/before/Shared/IOperationSource.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/IOperationSource.cs new file mode 100644 index 0000000000..1be2f9b733 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/IOperationSource.cs @@ -0,0 +1,14 @@ +// 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/dotnet-aot-compat/before/Shared/IUtf8JsonSerializable.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/IUtf8JsonSerializable.cs new file mode 100644 index 0000000000..5653e46093 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/IUtf8JsonSerializable.cs @@ -0,0 +1,14 @@ +// 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/dotnet-aot-compat/before/Shared/InitializationConstructorAttribute.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/InitializationConstructorAttribute.cs new file mode 100644 index 0000000000..d087b58c2a --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/InitializationConstructorAttribute.cs @@ -0,0 +1,15 @@ +// 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/dotnet-aot-compat/before/Shared/ManagedServiceIdentityTypeV3Converter.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/ManagedServiceIdentityTypeV3Converter.cs new file mode 100644 index 0000000000..b33c186e19 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/ManagedServiceIdentityTypeV3Converter.cs @@ -0,0 +1,53 @@ +// 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/dotnet-aot-compat/before/Shared/NextLinkOperationImplementation.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/NextLinkOperationImplementation.cs new file mode 100644 index 0000000000..d4dc0403e2 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/NextLinkOperationImplementation.cs @@ -0,0 +1,701 @@ +// 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/dotnet-aot-compat/before/Shared/NoValueResponseOfT.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/NoValueResponseOfT.cs new file mode 100644 index 0000000000..95fa1e2573 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/NoValueResponseOfT.cs @@ -0,0 +1,39 @@ +// 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/dotnet-aot-compat/before/Shared/OperationFinalStateVia.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/OperationFinalStateVia.cs new file mode 100644 index 0000000000..8ad2396db9 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/OperationFinalStateVia.cs @@ -0,0 +1,16 @@ +// 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/dotnet-aot-compat/before/Shared/OperationInternal.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/OperationInternal.cs new file mode 100644 index 0000000000..2435465459 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/OperationInternal.cs @@ -0,0 +1,263 @@ +// 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/dotnet-aot-compat/before/Shared/OperationInternalBase.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/OperationInternalBase.cs new file mode 100644 index 0000000000..dad6480c22 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/OperationInternalBase.cs @@ -0,0 +1,234 @@ +// 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/dotnet-aot-compat/before/Shared/OperationInternalOfT.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/OperationInternalOfT.cs new file mode 100644 index 0000000000..c1adc58603 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/OperationInternalOfT.cs @@ -0,0 +1,431 @@ +// 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/dotnet-aot-compat/before/Shared/OperationPoller.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/OperationPoller.cs new file mode 100644 index 0000000000..4cbd975ebb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/OperationPoller.cs @@ -0,0 +1,114 @@ +// 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/dotnet-aot-compat/before/Shared/Page.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/Page.cs new file mode 100644 index 0000000000..1438fdfd5f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/Page.cs @@ -0,0 +1,16 @@ +// 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/dotnet-aot-compat/before/Shared/PageableHelpers.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/PageableHelpers.cs new file mode 100644 index 0000000000..4d15951fef --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/PageableHelpers.cs @@ -0,0 +1,556 @@ +// 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/dotnet-aot-compat/before/Shared/PropertyReferenceTypeAttribute.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/PropertyReferenceTypeAttribute.cs new file mode 100644 index 0000000000..141b350a5e --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/PropertyReferenceTypeAttribute.cs @@ -0,0 +1,52 @@ +// 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/dotnet-aot-compat/before/Shared/ProtocolOperation.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/ProtocolOperation.cs new file mode 100644 index 0000000000..ce76a07848 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/ProtocolOperation.cs @@ -0,0 +1,78 @@ +// 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/dotnet-aot-compat/before/Shared/RawRequestUriBuilder.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/RawRequestUriBuilder.cs new file mode 100644 index 0000000000..f48b1f6ed6 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/RawRequestUriBuilder.cs @@ -0,0 +1,229 @@ +// 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/dotnet-aot-compat/before/Shared/ReferenceTypeAttribute.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/ReferenceTypeAttribute.cs new file mode 100644 index 0000000000..04e86cc394 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/ReferenceTypeAttribute.cs @@ -0,0 +1,36 @@ +// 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/dotnet-aot-compat/before/Shared/SequentialDelayStrategy.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/SequentialDelayStrategy.cs new file mode 100644 index 0000000000..5185fa1201 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/SequentialDelayStrategy.cs @@ -0,0 +1,38 @@ +// 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/dotnet-aot-compat/before/Shared/SerializationConstructorAttribute.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/SerializationConstructorAttribute.cs new file mode 100644 index 0000000000..fbe9465541 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/SerializationConstructorAttribute.cs @@ -0,0 +1,15 @@ +// 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/dotnet-aot-compat/before/Shared/SharedExtensions.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/SharedExtensions.cs new file mode 100644 index 0000000000..215fd316e5 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/SharedExtensions.cs @@ -0,0 +1,82 @@ +// 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/dotnet-aot-compat/before/Shared/TaskExtensions.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/TaskExtensions.cs new file mode 100644 index 0000000000..9748653782 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/TaskExtensions.cs @@ -0,0 +1,313 @@ +// 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/dotnet-aot-compat/before/Shared/TypeFormatters.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/TypeFormatters.cs new file mode 100644 index 0000000000..6bb51d611c --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/TypeFormatters.cs @@ -0,0 +1,159 @@ +// 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/dotnet-aot-compat/before/Shared/TypeReferenceTypeAttribute.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/TypeReferenceTypeAttribute.cs new file mode 100644 index 0000000000..dce5c4f331 --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/TypeReferenceTypeAttribute.cs @@ -0,0 +1,41 @@ +// 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/dotnet-aot-compat/before/Shared/VoidValue.cs b/tests/dotnet/dotnet-aot-compat/before/Shared/VoidValue.cs new file mode 100644 index 0000000000..cb52e0eafb --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/Shared/VoidValue.cs @@ -0,0 +1,10 @@ +// 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/dotnet-aot-compat/before/autorest.md b/tests/dotnet/dotnet-aot-compat/before/autorest.md new file mode 100644 index 0000000000..3735f0952b --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/autorest.md @@ -0,0 +1,839 @@ +# 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/dotnet-aot-compat/before/global.json b/tests/dotnet/dotnet-aot-compat/before/global.json new file mode 100644 index 0000000000..3be1c15acd --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/before/global.json @@ -0,0 +1,6 @@ +{ + "sdk": { + "version": "9.0.300", + "rollForward": "latestFeature" + } +} diff --git a/tests/dotnet/dotnet-aot-compat/eval.yaml b/tests/dotnet/dotnet-aot-compat/eval.yaml new file mode 100644 index 0000000000..a2505c539f --- /dev/null +++ b/tests/dotnet/dotnet-aot-compat/eval.yaml @@ -0,0 +1,20 @@ +scenarios: + - name: "Make Azure.ResourceManager AOT-compatible" + prompt: "Make the project in the before/ directory AOT-compatible. Do not consult the after/ directory." + setup: + copy_test_files: true + assertions: + - type: "file_contains" + path: "before/Azure.ResourceManager.csproj" + value: "IsAotCompatible" + expect_tools: ["bash", "dotnet"] + 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." + timeout: 1050